SlideShare a Scribd company logo
1 of 24
Data File Handling
in C++
Edited by:
Dr. Muhammad Tanvir Afzal
Computer Science
Muhammad Ali Jinnah University
Islamabad
A
A
A
A
A
A
All rights reserved 2
Topics - Agenda
• Introduction
• Opening & closing of files
• Stream state member functions
• File operations
• Binary file operations
• Random access file operations
• Conclusion
All rights reserved 3
Introduction
• Computer programs are associated to work
with files as it helps in storing data &
information permanently.
• File - itself a bunch of bytes stored on
some storage devices.
• In C++ this is achieved through a
component header file called fstream.h
• The I/O library manages two aspects- as
interface and for transfer of data.
• The library predefine a set of operations
for all file related handling through certain
classes.
The fstream.h header file
Streams act as an interface between files and
programs.
They represent as a sequence of bytes and deals with
the flow of data.
Every stream is associated with a class having member
functions and operations for a particular kind of data
flow.
File  Program ( Input stream) - reads
Program  File (Output stream) – write
All designed into fstream.h and hence needs to be
included in all file handling programs.
Diagrammatically as shown in next slide
All rights reserved 5
File Handling Classes
Hierarchy Diagram
Why to use Files:
•Convenient way to deal large quantities of data.
•Store data permanently (until file is deleted).
•Avoid typing data into program multiple times.
•Share data between programs.
We need to know:
how to "connect" file to program
how to tell the program to read data
how to tell the program to write data
error checking and handling EOF
All rights reserved 9
// Initial experience reading and writing files
#include <fstream.h>
#include <iostream.h>
#include <stdlib.h>
int main()
{ ifstream in_stream;
ofstream out_stream;
int num;
in_stream.open("numbers.dat");
if (in_stream.fail()) { cout << "Input file could not be opened.n";
exit(1); }
out_stream.open("squares.dat");
if (out_stream.fail()) { cout <<"Output file could not opened.n";
exit(1); }
in_stream >> num;
out_stream << "The square of " << num << " is " <<num * num;
in_stream.close();
out_stream.close();
}
File Handling Classes
• When working with files in C++, the following
classes can be used:
– ofstream – writing to a file
– ifstream – reading for a file
– fstream – reading / writing
• What does it all have to do with cout?
– When ever we include <iostream.h>, an ostream
object, pointing to stdout is automatically defined –
this object is cout.
• ofstream inherits from the class ostream
(standard output class).
• ostream overloaded the operator >> for standard
output.…thus an ofstream object can
use methods and operators defined in
ostream.
Opening & Closing a File
 A file can be open by the method “open()” or
immediately in the constructor (the natural and
preferred way).
void ofstream / ifstream::open(const char* filename, int mode);
 filename – file to open (full path or local)
 mode – how to open (1 or more of following – using | )
ios::app – append
ios::ate – open with marker at the end of the file
ios::in / ios::out – (the defaults of ifstream and
ofstream)
ios:nocreate / ios::noreplace – open only if the file
exists / doesn’t exist
ios::trunc – open an empty file
ios::binary – open a binary file (default is textual)
 Don’t forget to close the file using the method
“close()”
All rights reserved 12
1: To access file handling routines:
#include <fstream.h>
2: To declare variables that can be used to access file:
ifstream in_stream;
ofstream out_stream;
3: To connect your program's variable (its internal name) to
an external file (i.e., on the Unix file system):
in_stream.open("infile.dat");
out_stream.open("outfile.dat");
4: To see if the file opened successfully:
if (in_stream.fail())
{ cout << "Input file open failedn";
exit(1); // requires <stdlib.h>}
All rights reserved 13
5: To get data from a file (one option), must declare
a variable to hold the data and then read it using the
extraction operator:
int num;
in_stream >> num;
[Compare: cin >> num;]
6: To put data into a file, use insertion operator:
out_stream << num;
[Compare: cout << num;]
NOTE: Streams are sequential – data is read and
written in order – generally can't back up.
7: When done with the file:
in_stream.close();
out_stream.close();
Stream state member functions
•In C++, file stream classes inherit a stream state
member from the ios class, which gives out the
information regarding the status of the stream.
For e.g.:
–eof() –used to check the end of file character
–fail()- used to check the status of file at opening
for I/O
–bad()- used to check whether invalid file
operations or unrecoverable error .
–good()- used to check whether the previous file
operation has been successful
File operations
The following member functions are used
for reading and writing a character from a
specified file.
get()- is used to read an alphanumeric
character from a file.
put()- is used to write a character to a
specified file or a specified output stream
Reading /Writing from/to
Binary Files
• To write n bytes:
– write (const unsigned char* buffer, int n);
• To read n bytes (to a pre-allocated buffer):
– read (unsighed char* buffer, int num)
#include <fstream.h>
main()
{
int array[] = {10,23,3,7,9,11,253};
ofstream OutBinaryFile("my_b_file.txt“, ios::out |
ios::binary);
OutBinaryFile.write((char*) array, sizeof(array));
OutBinaryFile.close();
}
All rights reserved 17
C++ has some low-level facilities for character I/O.
char next1, next2, next3;
cin.get(next1);
Gets the next character from the keyboard. Does not skip over
blanks or newline (n). Can check for newline (next == 'n')
Example:
cin.get(next1);
cin.get(next2);
cin.get(next3);
Predefined character functions must #include <ctype.h> and can be
used to
convert between upper and lower case
test whether in upper or lower case
test whether alphabetic character or digit
test for space
CHARACTER I/O
All rights reserved 18
//#include, prototypes, void main() omitted for space
ifstream fin;
char Chem1, Chem2;
double ratio;
fin.open("input.dat"); // open error check omitted for space
fin.get(Chem1);
while (!fin.eof())
{
if (isdigit(Chem1))
cout << "Test Code: " << Chem1 << endl;
else
{
fin >> ratio;
fin.get(Chem2);
Chem2 = toupper(Chem2);
cout << "Ratio of " << Chem1 << " to " << Chem2 << " is " << ratio << endl;
}
new_line(fin);
fin.get(Chem1);
}
}
void new_line(istream& in)
{
char symbol;
do {
in.get(symbol);
} while (symbol != 'n');
}
Reading /Writing from/to Textual Files
• To write:
– put() – writing single
character
– << operator – writing
an object
• To read:
– get() – reading a
single character of a
buffer
– getline() – reading a
single line
– >> operator –
reading a object
#include <fstream.h>
main()
{
// Writing to file
ofstream OutFile("my_file.txt");
OutFile<<"Hello "<<5<<endl;
OutFile.close();
int number;
char dummy[15];
// Reading from file
ifstream InFile("my_file.txt");
InFile>>dummy>>number;
InFile.seekg(0);
InFile.getline(dummy,sizeof(dummy));
InFile.close();
}
All rights reserved 20
Binary file operations
In connection with a binary file, the file
mode must contain the ios::binary mode
along with other mode(s)
To read & write a or on to a binary
file, as the case may be blocks of
data are accessed through the use
of C++ read() and write()
respectively.
All rights reserved 21
Random access file
operations
Every file maintains two internal pointers:
get_pointer and put_pointer
They enable to attain the random access in file
otherwise which is sequential in nature.
In C++ randomness is achieved by manipulating
certain functions
Moving within the File
• seekg() / seekp() – moving the reading
(get) / writing (put) marker
– two parameters: offset and anchor
• tellg() / tellp() – getting the position
of the reading (get) / writing (put)
marker
All rights reserved 23
EOF and File I/O Within Functions
When using a file within a function, the file parameter
MUST BE a reference parameter:
int read_file(ifstream& infile);
As with keyboard input, it is often desirable to process
some unknown amount of data. We use the end-of-file
(EOF) to accomplish this. EOF is automatically included
in text files we create.
Can test for EOF in several ways.
while (in_stream >> num)
OR
in_stream >> num; // priming read
while (! in_stream.eof())
{loop body
in_stream >> num;}
All rights reserved 24
Summary
• Files in C++ are interpreted as a sequence of
bytes stored on some storage media.
• Bases classes are used to perform I/O
operations.
• The data of a file is stored in either
readable form or in binary code called as
text file or binary file.
• The flow of data from any source to a sink
is called as a stream.
All rights reserved 25
1. When getting data from a file, there is no need to prompt for input.
2. One program may have multiple input and/or output files, and may
intermix keyboard/ display I/O with file I/O.
3. The file name may be obtained from the user, rather than hard coded in
the program.
4. The layout of a program's output is called the format. A variety of options
are available for controlling the appearance of the output.
5. Flags to control floating point display:
• out_stream.setf(ios::fixed);
• out_stream.setf(ios::showpoint);
• out_stream.precision(2);
6. rd_state() – returns a variable with one or more (check with AND) of the
following options:
• ios::goodbit – OK
• ios::eofbit – marker on EOF
• ios::failbit – illegal action, but alright to continue
• ios:badbit – corrupted file, cannot be used.
7. We can also access the bit we wish to check with eof(), good(), fail(),
bad(),
8. clear() is used to clear the status bits (after they were checked).
More Information on File I/O

More Related Content

What's hot (20)

Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
File in cpp 2016
File in cpp 2016 File in cpp 2016
File in cpp 2016
 
Files in c++
Files in c++Files in c++
Files in c++
 
Cpp file-handling
Cpp file-handlingCpp file-handling
Cpp file-handling
 
17 files and streams
17 files and streams17 files and streams
17 files and streams
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
Filesin c++
Filesin c++Filesin c++
Filesin c++
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
working file handling in cpp overview
working file handling in cpp overviewworking file handling in cpp overview
working file handling in cpp overview
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Filehadnling
FilehadnlingFilehadnling
Filehadnling
 
File Pointers
File PointersFile Pointers
File Pointers
 
08. handling file streams
08. handling file streams08. handling file streams
08. handling file streams
 
file handling c++
file handling c++file handling c++
file handling c++
 
file handling, dynamic memory allocation
file handling, dynamic memory allocationfile handling, dynamic memory allocation
file handling, dynamic memory allocation
 
File Handling and Command Line Arguments in C
File Handling and Command Line Arguments in CFile Handling and Command Line Arguments in C
File Handling and Command Line Arguments in C
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 

Similar to Data file handling

File management in C++
File management in C++File management in C++
File management in C++apoorvaverma33
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++Shyam Gupta
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdfTigabu Yaya
 
Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O YourHelper1
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Rex Joe
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceanuvayalil5525
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5YOGESH SINGH
 
Basics of files and its functions with example
Basics of files and its functions with exampleBasics of files and its functions with example
Basics of files and its functions with exampleSunil Patel
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfsudhakargeruganti
 
File management
File managementFile management
File managementsumathiv9
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operationsTAlha MAlik
 

Similar to Data file handling (20)

Data file handling
Data file handlingData file handling
Data file handling
 
File management in C++
File management in C++File management in C++
File management in C++
 
Stream classes in C++
Stream classes in C++Stream classes in C++
Stream classes in C++
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
Files and streams
Files and streamsFiles and streams
Files and streams
 
C_and_C++_notes.pdf
C_and_C++_notes.pdfC_and_C++_notes.pdf
C_and_C++_notes.pdf
 
Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O Linux System Programming - Buffered I/O
Linux System Programming - Buffered I/O
 
COM1407: File Processing
COM1407: File Processing COM1407: File Processing
COM1407: File Processing
 
Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01Filesinc 130512002619-phpapp01
Filesinc 130512002619-phpapp01
 
Files in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for referenceFiles in C++.pdf is the notes of cpp for reference
Files in C++.pdf is the notes of cpp for reference
 
Chapter4.pptx
Chapter4.pptxChapter4.pptx
Chapter4.pptx
 
VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5VIT351 Software Development VI Unit5
VIT351 Software Development VI Unit5
 
Basics of files and its functions with example
Basics of files and its functions with exampleBasics of files and its functions with example
Basics of files and its functions with example
 
File handling in C
File handling in CFile handling in C
File handling in C
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdfEASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
 
File management
File managementFile management
File management
 
Cs1123 10 file operations
Cs1123 10 file operationsCs1123 10 file operations
Cs1123 10 file operations
 
OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)OOPs & C++(UNIT 5)
OOPs & C++(UNIT 5)
 

More from TAlha MAlik

Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structuresTAlha MAlik
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointersTAlha MAlik
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functionsTAlha MAlik
 
Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_ifTAlha MAlik
 
Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constantsTAlha MAlik
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overviewTAlha MAlik
 
Cs1123 2 comp_prog
Cs1123 2 comp_progCs1123 2 comp_prog
Cs1123 2 comp_progTAlha MAlik
 
Cs1123 9 strings
Cs1123 9 stringsCs1123 9 strings
Cs1123 9 stringsTAlha MAlik
 

More from TAlha MAlik (11)

Cs1123 12 structures
Cs1123 12 structuresCs1123 12 structures
Cs1123 12 structures
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
 
Cs1123 8 functions
Cs1123 8 functionsCs1123 8 functions
Cs1123 8 functions
 
Cs1123 6 loops
Cs1123 6 loopsCs1123 6 loops
Cs1123 6 loops
 
Cs1123 7 arrays
Cs1123 7 arraysCs1123 7 arrays
Cs1123 7 arrays
 
Cs1123 5 selection_if
Cs1123 5 selection_ifCs1123 5 selection_if
Cs1123 5 selection_if
 
Cs1123 4 variables_constants
Cs1123 4 variables_constantsCs1123 4 variables_constants
Cs1123 4 variables_constants
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
Cs1123 2 comp_prog
Cs1123 2 comp_progCs1123 2 comp_prog
Cs1123 2 comp_prog
 
Cs1123 1 intro
Cs1123 1 introCs1123 1 intro
Cs1123 1 intro
 
Cs1123 9 strings
Cs1123 9 stringsCs1123 9 strings
Cs1123 9 strings
 

Recently uploaded

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 

Recently uploaded (20)

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 

Data file handling

  • 1. Data File Handling in C++ Edited by: Dr. Muhammad Tanvir Afzal Computer Science Muhammad Ali Jinnah University Islamabad A A A A A A
  • 2. All rights reserved 2 Topics - Agenda • Introduction • Opening & closing of files • Stream state member functions • File operations • Binary file operations • Random access file operations • Conclusion
  • 3. All rights reserved 3 Introduction • Computer programs are associated to work with files as it helps in storing data & information permanently. • File - itself a bunch of bytes stored on some storage devices. • In C++ this is achieved through a component header file called fstream.h • The I/O library manages two aspects- as interface and for transfer of data. • The library predefine a set of operations for all file related handling through certain classes.
  • 4. The fstream.h header file Streams act as an interface between files and programs. They represent as a sequence of bytes and deals with the flow of data. Every stream is associated with a class having member functions and operations for a particular kind of data flow. File  Program ( Input stream) - reads Program  File (Output stream) – write All designed into fstream.h and hence needs to be included in all file handling programs. Diagrammatically as shown in next slide
  • 7. Why to use Files: •Convenient way to deal large quantities of data. •Store data permanently (until file is deleted). •Avoid typing data into program multiple times. •Share data between programs. We need to know: how to "connect" file to program how to tell the program to read data how to tell the program to write data error checking and handling EOF
  • 8. All rights reserved 9 // Initial experience reading and writing files #include <fstream.h> #include <iostream.h> #include <stdlib.h> int main() { ifstream in_stream; ofstream out_stream; int num; in_stream.open("numbers.dat"); if (in_stream.fail()) { cout << "Input file could not be opened.n"; exit(1); } out_stream.open("squares.dat"); if (out_stream.fail()) { cout <<"Output file could not opened.n"; exit(1); } in_stream >> num; out_stream << "The square of " << num << " is " <<num * num; in_stream.close(); out_stream.close(); }
  • 9. File Handling Classes • When working with files in C++, the following classes can be used: – ofstream – writing to a file – ifstream – reading for a file – fstream – reading / writing • What does it all have to do with cout? – When ever we include <iostream.h>, an ostream object, pointing to stdout is automatically defined – this object is cout. • ofstream inherits from the class ostream (standard output class). • ostream overloaded the operator >> for standard output.…thus an ofstream object can use methods and operators defined in ostream.
  • 10. Opening & Closing a File  A file can be open by the method “open()” or immediately in the constructor (the natural and preferred way). void ofstream / ifstream::open(const char* filename, int mode);  filename – file to open (full path or local)  mode – how to open (1 or more of following – using | ) ios::app – append ios::ate – open with marker at the end of the file ios::in / ios::out – (the defaults of ifstream and ofstream) ios:nocreate / ios::noreplace – open only if the file exists / doesn’t exist ios::trunc – open an empty file ios::binary – open a binary file (default is textual)  Don’t forget to close the file using the method “close()”
  • 11. All rights reserved 12 1: To access file handling routines: #include <fstream.h> 2: To declare variables that can be used to access file: ifstream in_stream; ofstream out_stream; 3: To connect your program's variable (its internal name) to an external file (i.e., on the Unix file system): in_stream.open("infile.dat"); out_stream.open("outfile.dat"); 4: To see if the file opened successfully: if (in_stream.fail()) { cout << "Input file open failedn"; exit(1); // requires <stdlib.h>}
  • 12. All rights reserved 13 5: To get data from a file (one option), must declare a variable to hold the data and then read it using the extraction operator: int num; in_stream >> num; [Compare: cin >> num;] 6: To put data into a file, use insertion operator: out_stream << num; [Compare: cout << num;] NOTE: Streams are sequential – data is read and written in order – generally can't back up. 7: When done with the file: in_stream.close(); out_stream.close();
  • 13. Stream state member functions •In C++, file stream classes inherit a stream state member from the ios class, which gives out the information regarding the status of the stream. For e.g.: –eof() –used to check the end of file character –fail()- used to check the status of file at opening for I/O –bad()- used to check whether invalid file operations or unrecoverable error . –good()- used to check whether the previous file operation has been successful
  • 14. File operations The following member functions are used for reading and writing a character from a specified file. get()- is used to read an alphanumeric character from a file. put()- is used to write a character to a specified file or a specified output stream
  • 15. Reading /Writing from/to Binary Files • To write n bytes: – write (const unsigned char* buffer, int n); • To read n bytes (to a pre-allocated buffer): – read (unsighed char* buffer, int num) #include <fstream.h> main() { int array[] = {10,23,3,7,9,11,253}; ofstream OutBinaryFile("my_b_file.txt“, ios::out | ios::binary); OutBinaryFile.write((char*) array, sizeof(array)); OutBinaryFile.close(); }
  • 16. All rights reserved 17 C++ has some low-level facilities for character I/O. char next1, next2, next3; cin.get(next1); Gets the next character from the keyboard. Does not skip over blanks or newline (n). Can check for newline (next == 'n') Example: cin.get(next1); cin.get(next2); cin.get(next3); Predefined character functions must #include <ctype.h> and can be used to convert between upper and lower case test whether in upper or lower case test whether alphabetic character or digit test for space CHARACTER I/O
  • 17. All rights reserved 18 //#include, prototypes, void main() omitted for space ifstream fin; char Chem1, Chem2; double ratio; fin.open("input.dat"); // open error check omitted for space fin.get(Chem1); while (!fin.eof()) { if (isdigit(Chem1)) cout << "Test Code: " << Chem1 << endl; else { fin >> ratio; fin.get(Chem2); Chem2 = toupper(Chem2); cout << "Ratio of " << Chem1 << " to " << Chem2 << " is " << ratio << endl; } new_line(fin); fin.get(Chem1); } } void new_line(istream& in) { char symbol; do { in.get(symbol); } while (symbol != 'n'); }
  • 18. Reading /Writing from/to Textual Files • To write: – put() – writing single character – << operator – writing an object • To read: – get() – reading a single character of a buffer – getline() – reading a single line – >> operator – reading a object #include <fstream.h> main() { // Writing to file ofstream OutFile("my_file.txt"); OutFile<<"Hello "<<5<<endl; OutFile.close(); int number; char dummy[15]; // Reading from file ifstream InFile("my_file.txt"); InFile>>dummy>>number; InFile.seekg(0); InFile.getline(dummy,sizeof(dummy)); InFile.close(); }
  • 19. All rights reserved 20 Binary file operations In connection with a binary file, the file mode must contain the ios::binary mode along with other mode(s) To read & write a or on to a binary file, as the case may be blocks of data are accessed through the use of C++ read() and write() respectively.
  • 20. All rights reserved 21 Random access file operations Every file maintains two internal pointers: get_pointer and put_pointer They enable to attain the random access in file otherwise which is sequential in nature. In C++ randomness is achieved by manipulating certain functions
  • 21. Moving within the File • seekg() / seekp() – moving the reading (get) / writing (put) marker – two parameters: offset and anchor • tellg() / tellp() – getting the position of the reading (get) / writing (put) marker
  • 22. All rights reserved 23 EOF and File I/O Within Functions When using a file within a function, the file parameter MUST BE a reference parameter: int read_file(ifstream& infile); As with keyboard input, it is often desirable to process some unknown amount of data. We use the end-of-file (EOF) to accomplish this. EOF is automatically included in text files we create. Can test for EOF in several ways. while (in_stream >> num) OR in_stream >> num; // priming read while (! in_stream.eof()) {loop body in_stream >> num;}
  • 23. All rights reserved 24 Summary • Files in C++ are interpreted as a sequence of bytes stored on some storage media. • Bases classes are used to perform I/O operations. • The data of a file is stored in either readable form or in binary code called as text file or binary file. • The flow of data from any source to a sink is called as a stream.
  • 24. All rights reserved 25 1. When getting data from a file, there is no need to prompt for input. 2. One program may have multiple input and/or output files, and may intermix keyboard/ display I/O with file I/O. 3. The file name may be obtained from the user, rather than hard coded in the program. 4. The layout of a program's output is called the format. A variety of options are available for controlling the appearance of the output. 5. Flags to control floating point display: • out_stream.setf(ios::fixed); • out_stream.setf(ios::showpoint); • out_stream.precision(2); 6. rd_state() – returns a variable with one or more (check with AND) of the following options: • ios::goodbit – OK • ios::eofbit – marker on EOF • ios::failbit – illegal action, but alright to continue • ios:badbit – corrupted file, cannot be used. 7. We can also access the bit we wish to check with eof(), good(), fail(), bad(), 8. clear() is used to clear the status bits (after they were checked). More Information on File I/O