C++ Program to Read a File

In this article, you will learn and get code to read a file in C++. The program is created in a way that, receives the name of file from user as input, and reads all the content of given file.

This to do Before Program

To read a text file using a C++ program, a file inside the current directory must be created before executing the program of reading the content of a file.

That is, create a file named codescracker.txt with following content:

Hello C++
This is codescracker.txt File

and save this file inside the current directory. The current directory, means the directory where your C++ source code to read a file, is saved. Because I'm going to save the program given below, in a folder cpp programs of Documents of C-Drive. Here is the snapshot of the folder:

read a file in c++

And here is the snapshot of opened codescracker.txt file:

c++ read a file

Now let's move on and create a C++ program read this file's content.

Read a Text File in C++

This is the program to read the content of a text file in C++. The newly created file, codescracker.txt get read through this program:

using namespace std;
int main()
    char fileName[30], ch;
    fstream fp;
    cout<<"Enter the Name of File: ";
    fp.open(fileName, fstream::in);
        cout<<"\nError Occurred!";
        return 0;
    return 0;

This program was build and run under Code::Blocks IDE. Save this source code in the same folder, cpp programs where the file codescracker.txt is created. To save this source code in that folder, navigate to File→Save file as... in Code::Blocks and type the name of file and click on Save button as shown in the snapshot given below:

c++ read file

After saving the source code, here is its sample run. This is the initial output:

c++ read text file

Now supply the input say codescracker.txt as name of file, then press ENTER key to read it as shown in the snapshot given below:

read text file c++

Note - The statement, fp>>noskipws>>ch reads data from a file in character-by-character manner, without skipping white spaces.

Note - The fstream::in is file opening mode. It opens a file in reading mode only.

Same Program in Other Languages

C++ Online Test

« Previous Program Next Program »

Follow/Like Us on Facebook

Subscribe Us on YouTube