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 such a way that it receives the name of the file from the user as input and reads all the content of the given file.

This to do before the 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, gets read through this program:

#include<iostream>
#include<fstream>
#include<stdio.h>
using namespace std;
int main()
{
    char fileName[30], ch;
    fstream fp;
    cout<<"Enter the Name of File: ";
    gets(fileName);
    fp.open(fileName, fstream::in);
    if(!fp)
    {
        cout<<"\nError Occurred!";
        return 0;
    }
    cout<<"\n------"<<fileName<<"-------\n";
    while(fp>>noskipws>>ch)
        cout<<ch;
    fp.close();
    cout<<endl;
    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 a character-by-character manner, without skipping white spaces.

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

The same program in different languages

C++ Quiz


« Previous Program Next Program »


Liked this post? Share it!