A C++ program to use the ifstream class should begin as follows:
#include <iostream>
using namespace std;
The first line includes the header that has the definition of the ifstream class. The second line includes the iostream header that has the cout object for printing output to the terminal (console). The third line is a statement, and not a directive. The standard namespace is any name followed by “std:;”.
This article explains the use of the ifstream class of the fstream header, to handle input from a file in disk into a running program. The input is characters in sequence that go to a buffer in memory before reaching the program. In other words, this article explains how to read a text file, from the disk, in C++.
Creating an ifstream Object
In order to read the content of a file in disk, an ifstream object has to be instantiated from the ifstream class. The constructors commonly used by Anglo-Saxon (including Western European) programmers are:
explicit basic_ifstream(const char* s, ios_base::openmode mode = ios_base::in);
and
explicit basic_ifstream(const string& s, ios_base::openmode mode = ios_base::in);
The prefix, “basic_” can be omitted for all three syntaxes. The use of the first syntax here will be illustrated in the next section. In the second syntax, the first argument is a string literal or an array of characters ending in ‘\0’. This string is a directory path and filename, e.g. “dir1/txtFile.txt”, assuming that the program is in the home/user directory. For the second syntax, the first argument is the same as the first argument of the previous syntax, but it is a string of the string class (header). In both syntaxes, the second argument should be “ios_base::in” where “in” means for reading (input).
Illustration
A construction statement for the second syntax is as follows:
The name of the file whose content is to be read is, “txtFile.txt”. After this statement, the file “txtFile.txt” is considered open in the running program. When a file is opened, a sequence of consecutive characters that represent the file is in memory for buffer control.
A construction code segment for the third syntax is:
ifstream ifs = ifstream(str, ios_base::in);
In either situation, ifs is the ifstream object of the opened file. With the string type, do not forget to include the string class (header) into the program as follows:
Opening a File
A file is said to be opened when a sequence of consecutive characters of the file that represent the file is in memory for buffer control. The second and third construction syntaxes above open the file for reading, but the first syntax does not. That is, the second and third syntaxes do instantiation of the ifstream object and opening of file as well while the first syntax does only instantiation. The object ifs can be instantiated from the ifstream class using the first syntax with the statement:
In this case, a file object ifs has been created but the file is not yet opened. To open the file for reading, the open member function of the ifstream class has to be used. The open() overloaded methods commonly used by Anglo-Saxon (including Western European) programmers are:
void open(const string& s, ios_base::openmode mode = ios_base::in);
Note that the construction statement “ifstream ifs;” does not mention any file in the disk. And so the first and second arguments of these open() member functions have the same meanings as those for the second and third construction syntaxes above respectively.
Illustration
The use of the first open() member function here (in this section), can be illustrated as follows:
const char* str = "dir1/txtFile.txt";
ifs.open(str, ios_base::in);
The use of the second open() member function here (in this section) can be illustrated as follows:
string str = "dir1/txtFile.txt";
ifs.open(str, ios_base::in);
The difference in the two code segments are the ways the string for the path and filename are constructed.
Was the File Opened?
A file is said to be opened, when a sequence of consecutive characters of the file that represent the file is in memory for buffer control. What if the path and/or filename was wrong? What if the file could not be opened because the disk was bad and its sectors could not be read? It is advisable to always check if the file was opened using the syntax:
is_open() is a member function of the ifstream class. It returns true, if file was opened successfully, and false otherwise. The following code segment illustrates the use of this member function:
const char* str = "dir1/txtFile.txt";
ifs.open(str, ios_base::in);
if (ifs.is_open() == true)
cout << "File is opened." << endl;
else
cout << "File could not be open!" << endl;
The output should be:
Closing a File
A file should be closed after it has been opened. The closing action stops the buffer in memory, freeing memory space for other activities. It also breaks gracefully the connection it made with the file in disk. ifstream has the member function close() to close an opened file. The syntax is:
The following code segment illustrates its use:
if (ifs.is_open() == true) {
/* do something with the opened file here. */
ifs.close();
cout << "Opened File has been closed." << endl;
}
else
cout << "File could not be open!" << endl;
The output is:
The file should be used when the programmer is sure that it has been opened, then closed after that.
Reading Characters One-by-One
ifstream has a member function whose syntax is:
When it gets the next character, it puts it in the variable c and returns the ifstream’s object inherited from basic_istream. The internal pointer of ifstream then points to the next character for next reading. When the end-of-file is reached, the object returned is converted to false.
The following code segment reads all the characters in the file one-by-one and sends each to the terminal (console):
while (ifs.get(c))
cout << c;
C has to be declared first. C is the argument of get(), which is a member function of the ifstream object. The only simple statement (cout << c;) of the while compound statement sends a copy of the character to the output.
Instead of sending the characters to the output, they can be sent to a string object, forming a long string as follows:
string str;
while (ifs.get(c))
str.push_back(c);
In this case, the string header (library) has to be included into the program.
The following program reads all the content of a file and displays it:
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream ifs = ifstream("dir1/txtFile.txt", ios_base::in);
if (ifs.is_open() == true) {
char c;
string str;
while (ifs.get(c))
str.push_back(c);
cout << str<< endl;
ifs.close();
cout << "Opened File has been closed." << endl;
}
else
cout << "File could not be open!" << endl;
return 0;
}
Conclusion
The ifstream class of the fstream header handles input from a file from disk into a running program. To create an ifstream object, use any of the syntaxes:
explicit basic_ifstream(const char* s, ios_base::openmode mode = ios_base::in);
explicit basic_ifstream(const string& s, ios_base::openmode mode = ios_base::in);
If the first syntax is used, then the object still has to be opened, with any of the following member function syntaxes:
void open(const string& s, ios_base::openmode mode = ios_base::in);
To know if a file is successfully opened, use the member function syntax:
The ifstream object has to be closed after use.
To read the characters one-by-one, use in a while-loop, the member function syntax: