How to Read the Contents of a File in C++


In this article, we show how to read the contents of a file in C++.

So with C++, we can open files such as in any directory on our computer and read its contents.

This is true of many file formats, including text files (.txt), rich text format files (.rtf), HTML files (.html), as well as several other file formats.

C++ may not be able to open up and read very advanced file formats, such as .docx, however, without any additional tools.

The file we will read from is a text file (.txt) with a few lines that is shown here: file1.txt

So let's now go into our program of how we can read and output the contents of a file using C++. This is shown below.

We use the library to work with files. In this case, we are opening up a file and reading the contents of it.

We use the library to output an error message if the file, file1.txt, cannot be opened.

We use the library because we're going to be outputting the lines of string within the file that we read.

So we go to the main function.

Within this main function, the first thing we do is create a string, line.

We then create our connection to the file we want to read from, which in this case is "file1.txt". We do this by creating an ifstream reader object and then passing in the filename as its parameter. You create an ofstream writer object if you want to write to a file. You create an ifstream reader object if you want to read from a file.

We then create an error message if we are not able to open the file for reading purposes.

We then create a while loop.

The point of the while loop is that while there is still lines left in the file, we want to go through each of them. When C++ reads the contents of a file, it doesn't read the whole thing as one. It reads the file line by line until it reaches the last line. In fact, the eof() function which we use in this code stands for end of file. We create a while loop that goes until the reader reaches the end of file, and then it stops. So while the reader hasn't reached the end of file, we use the getline() function to read each line. We then output each line using the cout function.

When C++ reaches the end of file, the while loop terminates; thus, no more lines are read by the program.

We then close the reader object, as reading of the file is now finished.

After we read the contents of the file1.txt that we linked to above, the outputs look like the following below.

Reading the contents of a file in C++

And this is how to read the contents of a file in C++.

Related Resources

How to Write Contents to a File in C++

How to Append Contents to a File in C++

HTML Comment Box is loading comments...