codescracker


c++

C++ Program to Read and Display File



« Previous Program Next Program »


Read and Display File in C++

To read and display file's content in C++ programming, you have to first ask to the user to enter the file name with extension to open the file using the function open(), now start reading file's content character by character and display its content character by character at the time of reading on the output screen as shown here in the following program.

C++ Programming Code to Read and Display File's Content

In the below C++ program, we have created a file named file.txt with four line of text. Now let's see the below program to know how to read the file and display its content on the screen

Following C++ program ask to the user to enter file name (like file.txt) to read its content and display the content of this file on the screen:

/* C++ Program - Read and Display File */
		
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<fstream.h>
#include<stdlib.h>
void main()
{
	clrscr();
	ifstream ifile;
	char s[100], fname[20];
	cout<<"Enter file name to read and display its content (like file.txt) : ";
	cin>>fname;
	ifile.open(fname);
	if(!ifile)
	{
		cout<<"Error in opening file..!!";
		getch();
		exit(0);
	}
	while(ifile.eof()==0)
    {
        ifile>>s;
        cout<<s<<" ";
    }
	cout<<"\n";
	ifile.close();
	getch();
}

When the above C++ program is compile and executed, it will produce the following result:

C++ program read and display file content

Here the above C++ program ask to the user to enter file name (like file.txt) to read all the content present in the file and display all its content on the screen

Same Program in Other Language

You may like the same program in other programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test