C++ Files and Stream – File Handling – File I/O

File Read and Write

As you know, standard input and output operations are performed by using streams. The operations on files are performed by using streams too. For this purpose, three classes exist:

  • ofstream – stream used for output to files.
  • ifstream – stream used for input from files.
  • fstream – stream for both input and output operations.

fstream library

You have to include fstream library to be able to work with files:

#include <fstream>

In this tutorial, we will work with objects of fstream type. Class fstream encapsulates both properties of ifstream and ofstream classes.
In the case, you want to open file only for input operations, you have to use ifstream object. In the case, you want only to write to file, use ofstream object.

The first thing you need to work with file is to open it. Member function open of fstream class opens file and associates a stream with it:

void open (const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out);

The first parameter represents the path to the file. The second one represents mode to open a file.

File opening modes

There are different modes in which you can open a file:

  • in – file is opened for input.
  • out – file is opened for output.
  • binary – binary file is opened.
  • ate – output position is set to the end of the file when a file is opened.
  • app – all the outputs are appended to the existing contents of the file.
  • trunc – erase data from file.

The default value for fstream mode parameter is in | out. It means that file is opened for reading and writing when you use fstream class.
When you use ofstream class, default value for mode is out and the default value for ifstream class is in.

Look on the example of opening a file for reading and writing:

fstream file;
//open file text.txt for input and output
file.open("test.txt");

This line of code opens a stream that is now associated with file “test.txt” from the folder where your source file is located. If you will try to call open function for a stream that is already associated with a file, it will produce an error.

As is mentioned above, a stream is associated with a file. Therefore, you can perform basic input and output operations such as writing to file and reading from it. It is done in the same way as you work with cout and cin objects. You have to use extraction (>>) and insertion (<<) operators for this purpose:

//write ten numbers to test.txt
for (int i = 0; i != 10; ++i)
	file << i << endl;//write i with newline character to text.txt
file.seekg(ios::beg);//reset position of the input
//read first 5 number from test.txt
for (int i = 0; i != 5; ++i)
{
	int k;
	file >> k;//read an integer from file and save its value in k
	//show read value on screeen
	cout << k << endl;
}

The content of file test.txt after execution of this program is:

0
1
2
3
4
5
6
7
8
9

is_open

You can check, if the file is opened by using is_open member function:

bool is_open();

This function returns true if the file is opened and associated with this stream. Otherwise, it returns false:

fstream file;
//open file text.txt for input and output
file.open("test.txt");
if (!file.is_open())
	cout << " Cannot open file!" << endl;

close

File is closed by using close() member function:

void close();

This function closes the file and dissociate stream with this file:

	
//after all work with file is done
//close it
file.close();

get

You can extract characters from the stream when you open it for reading by using get() member functions. There are two possibilities to get unformatted input by using get() function:

  1. Extract single character
    char get();
    Single character code is returned.
  2. Extract C-string
    istream& get (char* str, int n, char delim = ‘\n’);
    Extract characters into str until n-1 characters are not extracted or delim character is not met.

Example:

fstream file;
//open file text.txt for input and output
file.open("test.txt");
if (!file.is_open())
	cout << " Cannot open file!" << endl;
//write ten numbers to test.txt
for (int i = 0; i != 10; ++i)
	file << i << endl;//write i with newline character to text.txt
file.seekg(ios::beg);//reset position of the input
//read first 5 number from test.txt
for (int i = 0; i != 5; ++i)
{
	//show read value on screeen
	cout << (char)file.get() << endl;
}

You will get the following output, because newline character is a character too and it is extracted in the same way as any simple character:

0
1
2

getline

getline() member function extracts a line into an array of characters pointed by str until n-1 characters are not extracted or delim character is not met:

istream& getline (char* str, streamsize n, char delim = ‘\n’);

ignore

ignore member function extracts characters from the file and ignores them until n characters are not extracted, delim or end of file (EOF) is not mat:

istream& ignore (int n = 1, int delim = EOF);

If EOF is reached, eofbit flag is set.

peek

Peek function returns the next characters in the stream, but does not extract it.

int peek();

putback

Putback function returns character c to stream:

putback (char c);

seekg

There is a possibility to set the position of the next extracted value from stream. It is done by using seekg functions:

seekg (int pos);

tellg

In the same time, you can get current position in file input stream with tellg function:

int tellg();

As its written above, insertion operator ( >> ) is used to write formatted data to file. In addition, you can use the following functions to perform writing to file:

  1. put (char c) – write character c to file.
  2. write (const char* str, int n) – write n characters from array of char that is pointed by str.
  3. int tellp() – returns position in output sequence.
  4. seekp(int pos) – sets the position in the output sequence.
  5. flush() – cleans the stream.

Here is an example of use member functions of fstream class:

fstream file;

//open file text.txt for input and output
file.open("test.txt");

//check if file is opened
if (!file.is_open())
	cout << " Cannot open file!" << endl;

//write a message to file
file << "This is the first line " << endl << "This is the second line" << endl;
file.seekg(ios::beg);//reset position of the input

//read first 5 number from test.txt
for (int i = 0; i != 5; ++i)
{
	//show read value on screeen
	cout << (char)file.get() << endl;
}

//get the next character from file
char next = file.get();
cout << "The next character is " << (char)next << endl;

//reset position again
file.seekg(ios::beg);
char* str = new char[50];

//extract first line into str
file.getline(str, 50);

//show first line
cout << str << endl;

//ignor next extracted character
file.ignore();

//show the next character without extracting it from file
cout << "Peek " << (char) file.peek() << endl;

//get current position
cout << "Current position is " << file.tellg() << endl;

//after all work with file is done
//close it
file.close();

This program provides the following output:

T
h
i
s

The next character is i
This is the first line
Peek h
Current position is 26

Translate »