Data File Handling C++




Data File Handling C++


The following texts are the property of their respective authors and we thank them for giving us the opportunity to share for free to students, teachers and users of the Web their texts will used only for illustrative educational and scientific purposes only.


All the information in our site are given for nonprofit educational purposes

The information of medicine and health contained in the site are of a general nature and purpose which is purely informative and for this reason may not replace in any case, the council of a doctor or a qualified entity legally to the profession.



Data File Handling C++


Data File Handling

Text file: A text file stores information in readable and printable form. Each line of text is terminated with an EOL (End of Line) character. Every time text file is read to written some internal character translation takes place.


Binary file: A binary file contains information in the non-readable form i.e. in the same format in which it is held in memory. Here there is no end of line character and so to read/write is fast in a binary file as no character translation takes place.


Stream: A stream is a general term used to name flow of data. Different streams are used to represent different kinds of data flow. There are three file I/O classes used for file read / write operations.

o ifstream - can be used for read operations.

o ofstream - can be used for write operations.

o fstream - can be used for both read & write operations.

The last one fstream class is more flexible one but it increases the compiler overheads and therefore it is always advised that we should use the most appropriate class for a data file to be opened.



This header includes the definitions for the stream classes ifstream, ofstream and fstream. In C++ file input / output facilities implemented through fstream.h header file. It contain predefines set of operation for handling file related input and output fstream.h class ties a file to the program for input and output operation.


Steps To Process A File

• Determine the type of link required.

• Declare a stream for the desired types of link.

• Attach the desired file to the declared stream.

• Process the file.

• Close the file link with stream.


File Modes And opening a file with file modes: This is an information given at the time of

opening or creation of a file. It decides that what we can do with the file. In the above program it is

important to note that we have not mentioned that whether the file is to be opened in reading or

writing mode but the program runs successfully. This is because of the default file mode associated

with ifstream and ofstream classes respectfully. Following are the file modes used in C++:

  • in : Read only mode. Used for reading purposes. This is default file mode for ‘ifstream’ class with this mode an existing file is opened with all its data intact. But if the file doesn’t exist then a blank file will be opened.
  • out: Write only mode. Used for writing purposes. This is default file mode for ‘ofstream’ class. With this mode an existing file with same name is replaced with a new blank file and the blank file is opened. In such a situation we will lost the old existing file. If the file doesn’t exit straight way a new blank is opened.
  • app: To append (add) data at the end of the file. This mode is used along with ‘out’ mode.
  • ate: To fix the file pointer at the end the of file when it is opened. With this we write data any where in the file even on the existing data by shifting the file pointer position.
  • nocreate: To open only an existing file. This mode can be used along with both ‘in’ and ‘out’ modes.
  • noreplace: To open only a non-existing file ( i.e. only a new file). This mode can be used along with both ‘in’ and ‘out’ modes.
  • trunc: With this mode all the data of the file is deleted and a blank file is opened.
  • Binary:  to open a file in binary mode


Few examples of file opening statements:

1. ifstream aFile(“StName.txt”);

Here file mode is ‘ios::in’ which has been passed implicitly.

2. ofstream X(“Story.dat”);

Here file mode is ‘ios::out’ which has been passed implicitly. Here a new blank “Story.txt”

file will be created and if it is already existing then all the data of the file will be lost.

3. fstream X(“Story.dat”,ios::in||ios::out); // Here we can both read from and write onto the file

4.  fstream X(“Story.dat”,ios::in||ios::nocreate);

Here a “Story.dat” will be opened for reading but only when the file is existing.

5. fstream X(“Story.dat”,ios::out||ios::noreplace);

Here a new “Story.dat” will be opened for writing but only when the file is non-existing.


Uses of cascaded operator (<< & >>) for reading and writing onto a text file:

Perhaps the easiest method to read and write from/to a file is with the help of cascaded ‘<<’

(insertion) and ‘>>’(extraction) operators.

 << : Used for writing onto the file

 >> : Used for reading from the file (does not take white spaces)


Functions like: open(), close(), get(), getline(), put(), tellg(), seekg(), tellp(), seekp(), read() and write()

Open(): This is member of all three classes we are using in file handling namely ifstream, of stream and fstream. We can open/create a file in ways. Either using the constructors or using the open()


e.g. i) ifstream X(“Story.txt”); // This method uses a constructor of class ifstream to create the file

ii) ifstream X;“Story.txt”); // This method uses member function open() of class ifstream to create the file. If you want to manage multiple file with same stream use open().

close() : This one is also member of three classes namely ifstream, ofstream and fstream. This function terminates the connection between the file and stream associated with it and before closing it flushes the buffer also.  e.g. ofstream X(“Story.txt”);    …..      X.close();

get(): This function is used to read a character from a file. It is member of ifstream class.

e.g. ifstream X(“Story.txt”);

char ch;


getline(): This is used for reading a line (string) from standard input device. This function receives

three parameters and their uses are as follows:

First parameter is a storage variable name where the string is stored.

Second parameter specifies the the length of the string to be read from the input buffer.

Third parameter is a delimiting character that specifies that after this character no other character from the input buffer will be read.      e.g. char s[30];          cin.getline(s,20,’*’);

Case1 If we enter “We are Indians.” Then ‘s’ will store “We are Indians.”

Case2 If we enter “We are*Indians.” Then ‘s’ will store “We are*”

Case3 If we enter “We are Indians. And we are proud of it.” Then ‘s’ will store “We are Indians. And “ ie 20 chars.

Case4 If we enter “We are Indians. And we are proud*of it.” Then ‘s’ will store “We are Indians. And “ ie 20 chars.

get pointer: A get pointer indicates the position in the file at which the next input is to occur.

put pointer: It indicates the position in the file at which the next output is to be placed.

put(): This one is a member of ofstream class and is used for writing a single character on to a

file.                 e.g. ofstream X(“Story.txt”);             X.put(‘P’);

tellg(): It gives the current get-file pointer (read mode) position in a data file.

tellp(): It gives the current put-file pointer (write mode) position in a data file.

seekg(): This is used to shift get-file pointer position in a data file.            e.g. ifstream X(“Story.txt”);


Here file pointer ‘X’ will be shifted 10 bytes in forward direction. To move the file pointer in

backward direction we pass a –ve no. This function receives one more parameter known as offset

that can be any of the three namely ios::beg, ios::end, and ios::cur.

ios::beg : To move the pointer from the beginning of the file.

ios::end : To move the pointer from the end of the file.

ios::cur : To move the pointer from the current position of the file pointer.

e.g. X.seekg(10,ios::beg); 10 bytes form the beginning of the file.

seekp(): Same as above only that it works with put-file pointer and is a member of ‘ofstream’ class.

read(): The read() function reads a fixed number of bytes from the specified stream and puts them in the

buffer. *)& Object, sizeof(Object));

write(): The write() function writes fixed number of bytes from a specific memory location to the specified


Stream_object.write((char *)& Object, sizeof(Object));


Both functions take two arguments.

• The first is the address of variable, and the second is the length of that variable in bytes. The address of

variable must be type cast to type char*(pointer to character type)

• The data written to a file using write( ) can only be read accurately using read( ).

Detecting end of file with or without using eof() function:

A file pointer in a data file keeps on moving or changing its position with every read(get-file pointer) or write(put-file pointer) operation. Following are the methods to find whether the file pointer has reached to end of the file or not.

while(!aFile.eof()) // checking for EOF OR  while(aFile) // checking for EOF

{ }

  • aFile.eof() returns true if aFile is at the EOF or false otherwise.
  • aFile returns false if aFile is at the EOF or true otherwise.


Read a text file                                                        Write a text file

Character                        fin.get(ch)//capable of white spaces                          fout.put(ch)

Char ch                 fin>>ch//will not take white spaces                          fout<<ch


Word                   fin>>wd                                                                   fout<<Wd<<’ ‘

Char wd[30]


Line                      fin.getline(str,80)                                                       fout<<str

Char str[80]          or fin.getline(str,80,’.’)                                             


                              Or fin.get(str,80,’\n’)




Some times during file operations, errors may creep in, to check for such errors  c++ file streams inherit ‘ stream state’ members from ios class that stores information on the status of a file that is being currently used. The current state is held in an integer, in which following flags are encoded

Bad()- returns  non zero if any unrecoverable error has occurred (otherwise 0). Here badbit is set to 1

Eof()- returns non zero if end of file is e encountered while reading; Here eofbit is 1

Fail()-returns non zero when an input/output operation(which can be recovered) has failed. Here failbit is 1

Good()-returns non zero if no error has occurred.  When it returns zero no further operations can be carried out. Here goodbit is set to 1

clear() – resets the error state so that further operations can be attempted.


Source :

Web site link:

Google key word : Data File Handling C++ file type : doc

Author : not indicated on the source document of the above text

If you are the author of the text above and you not agree to share your knowledge for teaching, research, scholarship (for fair use as indicated in the United States copyrigh low) please send us an e-mail and we will remove your text quickly.


Data File Handling C++


If you want to quickly find the pages about a particular topic as Data File Handling C++ use the following search engine:



Data File Handling C++


Please visit our home page Terms of service and privacy page




Data File Handling C++