Lecture 4 Notes: Reading From A File: //creating Object For Reading The Contents of File
Lecture 4 Notes: Reading From A File: //creating Object For Reading The Contents of File
Reading a text file is very easy using an ifstream (input file stream).
#include <fstream>
ifstream inFile;
3. Open the file stream. Path names in MS Windows use backslashes (\). Because the backslash
is also the string escape character, it must be doubled. If the full path is not given, most
systems will look in the directory that contains the object program. For example,
inFile.open("C:\\temp\\datafile.txt");
4. Check that the file was opened. For example, the open fails if the file doesn't exist, or if it
can't be read because another program is writing it. A failure can be detected with code like
that below using the ! (logical not) operator:
if (!inFile) {
5. Read from the stream in the same way as cin>>name (read from keyboard). For example,
inFile>>name; (read from file)
inFile>>marks;
6. Close the input stream. Closing is essential for output streams to be sure all information has
been written to the disk, but is also good practice for input streams to release system
resources and make the file available for other programs that might need to write it.
#include<fstream>
#include<iostream>
int main()
char fname[10];
char ch;
cin>>fname;
f1.open(fname); // opening the file using open( ) function and connecting it to the stream
if(f1.fail())
exit(1);
ch=(char)f1.get(); //get function returns the end of file and reads char by char
f1.close();
return 0;
YOU CAN OPEN MULTIPLE FILES WITH SINGLE STREAM OBJECT BUT MAKE SURE TO CLOSE THE FIRST
FILE BEFORE OPENING THE SECOND FILE.
fail( ) stream function is used to check whether a file has been opened for input or output
successfully. If file opening operation fails, then fail( ) returns a non-zero character.
eof( ) stream function is used to check whether the file pointer has reached the end of a file
character or not. If successful, it returns a nonzero otherwise returns 1.
#include<fstream>
#include<iostream>
int main()
{
ifstream f1; //creating object for reading the contents of file
char fname[10];
char ch;
if(f1.fail())
exit(1);
ch=(char)f1.get(); //get function returns the end of file and reads char by char
f1.close();
return 0;