File Handling in C++

File Handling in C++

C++ supports the concept of file handling. In this post we get a brief about working with files in C++.

Input & Output Streams.

The I/O systems of C++ handles file operations which are very much similar to console I/O operations. It uses file streams as an interface between the programs and the files. The streams that supply data to the program is known as input stream, while the stream that receives data from the program is known as output stream. In other words, input stream reads data from the file and the output stream writes data to the file.

The input operation involves the creation of an input stream & linking it with the program and the input file. Similarly, the output operation involves establishing an output stream and linking it to the program an the output file.

File Input and Output Stream

Classes available for File Operations in C++.

The I/O system of C++ contains a set of classes that defines the file handling methods. These includes ifstream, ofstream and fstream.

These classes are derived from fstreambase and the corresponding iostream.h class. These classes designed to manage the disk file, are declared in the fstream.h and therefore, we must include this file in any program that uses files.

Stream classes for file operations

Following table gives the details of file stream classes :

ClassContents
1. filebufIts purpose is to set the file buffers to read and write. Contains ‘openprot’ constant and used in the ‘open()’ of file stream classes. Also contains close() and open() as members.
2. fstreambaseProvides operations common to the file streams. Serves as a base for fstream, ofstream & ifstream classes. Contains open() & close() functions.
3. ifstreamProvides input operations and contains open() with default input mode. Inherits the functions get(), getline(), read(), seekg() and tellg() from istream.
4. ofstreamProvides output operations. Contains open() with default output mode. Inherits put(), seekp(), teelp() and write() functions from ostream.
5. fstreamProvides support for simultaneous input and output operations. Contains open() with default input mode. Inherits all the functions from istream and ostream classes through iostream.

Also Check : C/C++ Keywords and their uses.

File modes

Following table lists the file mode parameters and their meanings :

ParametersMeaning
1. ios::appAppend to end of file.
2. ios::ateGo to end of file on opening.
3. ios::binaryBinary file.
4. ios::inOpen a file for reading only.
5. ios::nocreateOpen fails if the file does not exist.
6. ios::noreplaceOpen fails if the file already exist.
7. ios::outOpen file for writing only.
8. ios::truncDelete contents of file if it exists.

How to open & close a file in C++.

Opening a file : The general format for opening a file is as –
file_stream_class stream_object;
stream_object.open(“Filename”);

Here we use ifstream class to read a stream of objects from a file and ofstream class to write a stream of objects in a file.

For example :
To open a file to read stream of object from ‘data’.
ifstream infile;
infile.open(“data”);
To open a file to write stream of object into ‘data’.
ofstream outfile;
outfile.open(“data”);

Closing a file : Function close() is used to close a file, which is opened for read, write or read and write operations
For example : ifline.close();

File Pointers

Each file has two associated pointers known as the file pointers. One of them is called the input pointer and the other is called the output pointer. We use these pointers to move through the files while reading or writing. The input pointer reads the content of a given file locations and the output pointer writes to a given file location.

Each time input or output operation takes place, compiler automatically calls appropriate pointer. Input pointer is also called as get pointer and output pointer is also called as put pointer.

Some functions related to file systems.

1. seekg() : This function moves the file pointer forward with given number of bytes. It has the form ‘seekg(unsgined int);‘.

e.g. ifstream inf(“xyz.dat”);
inf.seekg(10);

In the above example, seekg() moves the input pointer 10 bytes forward. seekg is associated with input pointer or get pointer.

2. seekp() : This function repositions file to a given number of bytes. This function is associated with the output pointer. Corresponding class to process this function is “ofstream” class. It has the form ‘seekp(unsgined int);‘.

e.g. oftream outf(“xyz.dat”);
outf.seekp(10);

In the above example, output pointer will point to the 10th byte in file, after execution of seekp(10);.

NOTE : We can use “seek” function with two arguments as :

seekg(offset, ref position);
seekg(offset, ref position);

Offset represents number of bytes file pointer is to be moved from the location specified by ref position.

The ref position can be one of the three constatns :

i) ios::beg – start of file.
ii) ios::cur – current position of pointer.
iii) ios::end – end of file.

3. tellg() : This function returns current file pointer position. This function is associated with the input file stream.

e.g. ifstream inf(“xyz.dat”);
inf.tellg(10);
int n;
n = inf.tellg();

In above example, tellg() will return value zero, because initially input pointer points to zeroth location.

4. tellp() : This function returns current file pointer position. This function is associated with the output file stream.

e.g. ofstream outf;
outf.open(“xyz”,ios::app);
int n;
n = outf.tellp();

In above example, file is opened in append mode, therefore file pointer points to end-of-file character. Hence, tellp() returns number of characters present in file xyz.

Input/Output functions available file handling in C++

i. put() : This function stores single character into file which object of ofstream specifies. It has the form : “ofstream object.put(character variable);

e.g. ofstream outf;
outf.open(“xyz”);
char c = ‘A’;
outf.put(c);

ii. get() : This function reads a character from a file which object of ofstream specifies. It has the form : “ifstream object.get(character variable);

e.g. char c;
ifstream inf(“xyz”);
while(inf.eof() == 0)
{
inf.get(c);
cout<<c;
}

iii. write() : It has the form : “write((char*)&variable, sizeof(variable));”

This function is used along with the object of ofstream and it is used to store data into file in binary mode i.e. general user cannot read data of file by using ‘type’ command. Here we convert all the variables of different type into (char*) i.e. pointer to character and second parameter is number of bytes we require to store given variable.

e.g.
struct s;
{
char n[20];
int t;
};
main()
{
struct s m;
ofstream outf(“xyz”);
cin>>m.n;
cin>>m.t;
outf.write((char*)&m, sizeof(m));
}

iv. read() : It has the form : “read((char*)&variable, sizeof(variable));

Data which is stored by using write() can be read by using read(). This function reads data in binary mode from file. This function is associated with ifstream object.

Generally, object and structures use read() and wirte() to store the records. These functions have two arguments. First is the address of varibale of any data type. But, data is converted into pointer to characters. The second parameter is size of that variable.

e.g.
struct s;
{
char n[20];
int t;
};
main()
{
ifstream inf(“xyz”);
struct m;
while(inf.eof() == 0)
{
read((char*)&m, sizeof(m));
cout<<“\n”<<m.n;
cout<<“\n”<<m.t;
}
}

Conclusion

So this was the concept of file handling in C++. We hope it was clear to you. If you have doubt regarding any of the concept or this post, do mention it in the comment section below. For daily updates do follow us on instagram.

Keep Programming!

ErrorFreeProgram.

Leave a Reply

Your email address will not be published. Required fields are marked *