codescracker


c++

C++ Program to Read File



« Previous Program Next Program »


Read File in C++

To read a file in C++ programming, you have to first open that file using the function open() and then start reading the file's content as shown here in the following program.

C++ Programming Code to Read File

First make a textual file named "filename.txt" in your BIN (for TurboC++ user) folder present inside TurboC++ directory, to open this file for reading.

Following C++ program opens a file named filename.txt to read the content present inside this file, if there is an error in opening a file then program puts a message on the screen for the error, and if the file will be read then it will display the file (content of the file) but this program limits to only one line of the file which is to be read. To know more, go to 2nd next program, which will clear your doubt, that program will read a file and display the contents of it. For now, go through the following program which will read a file and display its content on the screen:

/* C++ Program - Read a File */
		
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>
#include<fstream.h>
void main()
{
	clrscr();
	char c[1000];
	ifstream ifile;
	ifile.open("filename.txt") ;
	if(!ifile)
	{
		cout<<"Error in opening file..!!";
		getch();
		exit(1);
	}
	cout<<"Data in file = ";
	while(ifile.eof()==0)
	{
		ifile>>c;
		cout<<c<<" ";
	}
	ifile.close();
	getch();
}

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