Home / Cplusplus / Reading a Text File In C++

Reading a Text File In C++

Before learning this section We hope you know the Difference between void main ( ) and int main ( ). If you haven’t seen the section then please do so and come back here.
 
The program to read the text file that you created in the previous section is as follows:
 
 
>> is the extraction operator. As you know, it is used for obtaining an input from the keyboard along with the keyword cin (console in). Suppose you declare an integer x.
 
You get the value from the user using the statement: cin>> x ; What the user types is stored in the variable x.
 
Similarly in the above program what does the line in>>string>>num ; do? It reads from the stream in and stores what it read in the variable string and num. The process is as follows:
 
First of all, the file has been opened. String is a character array. The compiler reads the file (test.txt which has been opened). It reads the first 15 characters.
 
The first word in the file is First. After this it encounters a blank space. Hence the string is terminated (for details on why it doesn’t continue reading check the section: Beware of character arrays).
 
Hence the word First is stored in variable array string. Next comes a number. This gets stored in the variable num that you have declared.
 
Next statement is: cout<<string<<num<<endl;
 
It just displays on the screen what it read from the file. After this remember that the compiler has reached the end of the first line of the file. It automatically moves to the second line of the file. Hence when we repeat the statement:
 
in>>string>>num ;
 
the compiler will read the next line of the file. The process just repeats and Second and 2 are now stored in string and num. Finally, the compiler prints the second line of the file on the screen.
 
Modes of Opening Files
 
When you open a file (for writing or reading), there are 6 modes that you can use to specify how you want the file to be opened. The modes are:
 
Modes of Opening Files Description
ios::app causes all the output (or whatever you write) to be appended to the end of the file. This mode can be used only for files opened for output.
ios::ate Go to the end of the opened file.
ios::binary causes the file to be opened in binary mode (we’ll deal with binary later on).
ios::in specifies that the file is capable of input only.
ios::out specifies that the file is capable of output
ios::trunc causes contents of pre-existing file by same name to be destroyed.
 
So far we’ve seen the file opening as follows:
 
ofstream out;
 
out.open(“test”); // This means test is opened in normal mode.
 
By default this is the same as out.open(“test”, ios::out); // opened specifically for output
 
We can combine two modes as follows:
 
out.open(“test”, ios::out | ios::binary );