Data File Handling in C++
Data File Handling in C++
Data File Handling in C++
In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in fstream headerfile.
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
So we should include <fstream.h> header file .
4.eof(): its stands for end of file. It checks for the end-of-file condition before processing data read from an input
file stream.its a member of ifstream class.
Syntax: obj.eof();
Ex: while (!obj.eof( )) //if not at end of file, continue reading numbers
{
cout<<data<<endl; //print numbers to screen
obj>> data; //get next number from file
}
File handling in c++
We can open a file using any one of the following methods:
1. Using constructor (bypassing the file name in constructor at the time of object creation.)
2. Using the open() function.
1. Using constructor :
We know that a constructor of class initializes an object of its class when it (the object) is being created. Same way, the
constructors of stream classes (ifstream, ofstream, or fstream) are used to initialize file stream objects with the filenamespassed
to them. This is carried out as explained here:
To open a file named myfile as an input file (i.e., data will be need from it and no other operation like writing or modifying
would take place on the file).
we shall create a file stream object of input(read) type like:
ifstream fin(“myfile",[ ios::in]) ;
or
ifstream in(“myfile”);
we shall create a file stream object of output(write) type like:
ofstream fout ("myfile",[ ios::out]) ;
or
ofstream out (“myfile”);
File handling in c++
Ex:
#include<fstream.h>
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
There are some mode flags used for file opening. These are:
•ios::app: append mode
•ios::ate: open a file in this mode for output and read/write controlling to the end of the file
•ios::in: open file in this mode for reading
•ios::out: open file in this mode for writing
•ios::trunk: when any file already exists, its contents will be truncate.
1. seekg(): seekg() is used to move the get pointer to a desired location with respect to a reference point.
Syntax: file_pointer.seekg (number of bytes ,Reference point);
Example: fin.seekg(10,ios::beg);
2. seekp(): seekp() is used to move the put pointer to a desired location with respect to a reference point.
Syntax: file_pointer.seekp(number of bytes ,Reference point);
Example: fout.seekp(10,ios::beg);
File handling in c++
3. tellg(): tellg() is used to know where the get pointer is in a file.
Syntax: file_pointer.tellg();
Example: int posn = fin.tellg();