x

C++ File Handling

PREV     NEXT

C++ File Handling:


What is File Handling?

  • In C++, file handling is done using file streams where file means it is used to store the information or data and streams refer to sequence of bytes.
  • In files we store data i.e. text or binary data permanently and use these data to read and write in the form of input and output operations by transferring the bytes of data.
  • So, till now we were using iostream standard library, which provides cin for reading from the provided input and cout for writing to the standard output.

In C++, the files are handled by using three classes’ ifstream, ofstream and fstream and the header file fstream is used.

Let us discuss these three streams:

  • ifstream: It type represents the input file stream and it is used to read the data from the files.
  • ofstream: It represents the output file stream and is used to create files and to write data to files.
  • fstream: It represents the file stream and has the features of both the streams ifstream and ofstream which means it can create files, write the information to file and read the information from files.

Operations in File Handling

Let us have a look at the operations in file handling:

Creating or Opening a file

We can create or open a file by giving a specific path of the file and mode of operation. The operations than can be performed are reading, writing, appending and truncating.


Syntax for creating a file is:

FilePointer.open(“Path”,ios::mode);

There are some different modes in which we can open a file:

  • ios::app      – It opens a text file for appending which means we can add the text at the end.
  • ios::in         – It opens a text file for reading.
  • ios::out       – It opens a text file for writing.
  • ios::trunc   – It truncates the content before opening a file, if file exists.
  • ios::ate        – It opens a file for output and move the read/write control to the end of the file.

In this code we have opened the file ‘abc.txt’ to write on it. ‘abc.txt’ file must be created in your working directory. You can also open the file in both reading and writing purpose.

Let us have a look at the example:

Closing a file:

When the C++ program terminates it automatically flush all the streams release all the allocated memory and close all the opened files.

Reading and Writing on a File:

In reading and writing from a file we use >> and << operator respectively.

Let us have a look at the example to understand this:



Like it? Please Spread the word!