C++ Data File Handling


File: The information / data stored under a specific name on a storage device, is called a file.

Stream: It refers to a sequence of bytes.

Text file: It is a file that stores information in ASCII characters. In text files, each line of text is terminated with a special character known as EOL (End of Line) character or delimiter character. When this EOL character is read or written, certain internal translations take place.

Binary file: It is a file that contains information in the same format as it is held in memory. In binary files, no delimiters are used for a line and no translations occur here.


Classes for file stream operation

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.


Opening a file

Opening file using open()

Syntax

Stream-object.open("filename", mode)
ofstream ofile;
file.open("data1");
ifstream ifile;
ifile.open("data2");
File mode parameter Meaning
ios::app Append to end of file
ios::ate go to end of file on opening
ios::binary file open in binary mode
ios::in open file for reading only
ios::out open file for writing only
ios::nocreate open fails if the file does not exist
ios::noreplace open fails if the file already exist

All these flags can be combined using the bitwise operator OR (|).

For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open():

fstream file;
file.open (example.bin", ios::out | ios::app | ios::binary);

Closing File

fout.close();
fin.close();

INPUT AND OUTPUT OPERATION

get() function :- The function get() reads a single character form the associated stream.

put() function :- The function put() writes a single character to the associated stream.

Example

file.get(ch);
file.put(ch);

Syntax of get()

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream infile;
Char ch;
infile.open("text");
------------
-------------
While(! inflie.eof())
{
Ch=infile.get();
------
------
}
}

Syntax of put()

 #include <iostream>
#include <fstream>
using namespace std;

int main()
{
ofstream outfile;
Char ch;
outfile.open("text");
------------
-------------
While(! outflie.eof())
{
Ch=infile.get();
cout.put(ch) //display a character onto a screen 
------
------
}
}

STREAM STATE MEMBER FUNCTION

The Stream state member function give the information status like end of file has been reached or file failure.
ERROR HANDLING FUNCTION
FunctionRETURN VALUE AND MEANING
eof()returns true (non zero) if end of file is encountered while reading; otherwise return false(zero)
fail()return true when an input or output operation has failed
bad()returns true if an invalid operation is attempted or any unrecoverable error has occurred.
good()returns true if no error has occurred.

Share this article on