0% found this document useful (0 votes)
5 views

11. Working With Files

The document provides an overview of file handling in C++, detailing the operations for reading and writing files using file streams. It explains the use of classes such as ifstream, ofstream, and fstream for file manipulation, as well as the importance of error handling and detecting end-of-file conditions. Additionally, it covers functions for random access and sequential input/output operations, along with examples of file operations in C++.

Uploaded by

shivani.garg
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

11. Working With Files

The document provides an overview of file handling in C++, detailing the operations for reading and writing files using file streams. It explains the use of classes such as ifstream, ofstream, and fstream for file manipulation, as well as the importance of error handling and detecting end-of-file conditions. Additionally, it covers functions for random access and sequential input/output operations, along with examples of file operations in C++.

Uploaded by

shivani.garg
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Working with Files

Files
• A file is a collection of related data stored in a particular area on the
disk.
• Programs can be designed to perform the read and write operations
on these files.
• A program typically involves either or both of the following kinds of
data communication:
1. Data transfer between the console unit and the program.
2. Data transfer between the program and a disk file.
Console-program-file Interaction
• The I/O system of C++ handles file operations which are very much
similar to the console input and output operations. It uses file streams
as an interface between the programs and the files.
• The stream that provides data to the program is known as input
stream and the one that receives data from the program is known as
output stream.
• The input stream extracts (or reads) data from the file and the output
stream inserts (or writes) data to the file.
Classes for File Stream Operations
Opening and Closing a File
• For opening a file, we must create a file stream and then link it to the
filename.
• A file stream can be defined using the classes ifstream, ofstream and
fstream that are contained in the header file fstream.
• The class to be used depends upon the purpose, that is whether we
want to read data from the file or write data to it.
• A file can be opened in two ways:
1. Using the constructor function of the class.
2. Using the member function open() of the class.
• The first method is useful when we use only one file in the stream. The
second method is used when we want to manage multiple files using
one stream.
Opening Files using Constructor
• A constructor is used to initialize an object while it is being created. In
this case, a filename is used to initialize the file stream object.
• Following steps are involved in this process:
1. Create a file stream object to manage the stream using the appropriate class.
The class ofstream is used to create the output stream and the class ifstream
is used to create the input stream.
2. Initialize the file object with the desired filename.
• For example, the following statement opens a file named “results” for
output:
ofstream outfile(“results”);
• This creates outfile as an ofstream object that manages the output
stream.
Two file streams working on separate files
• Similarly, the following statement declares infile as an ifstream object
and attaches it to the file, “data”, for reading.
ifstream infile(“data”);
• The connection with a file is closed automatically when the stream
object expires (when the program terminates).
//Creating files with constructor function
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream outf(“ITEM”); //connect ITEM file to outf
cout<<“Enter item name:”;
char name[30];
cin>>name; //get name from keyboard
outf<<name<<“\n”; //write to file ITEM
cout<<“Enter item cost:”;
float cost;
cin>>cost; //get cost from keyboard
outf<<cost<<“\n”; //write to file ITEM
outf.close(); //disconnect ITEM file from outf
ifstream inf(“ITEM”); //connect ITEM file to inf
inf>>name; //read name from file ITEM
inf>>cost; //read cost from file ITEM
cout<<“\n”;
Output:
cout<<“Item name:”<<name<<“\n”; Enter item name: CD-ROM
cout<<“Item cost:”<<cost<<“\n”; Enter item cost: 250
inf.close();
Item name: CD-ROM
return 0; Item cost: 250
}
Opening Files using open()
//Creating files with open() function
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream fout; //create output stream
fout.open(“country”); //connect “country” to it
fout<<“United States of America\n”;
fout<<“United Kingdom\n”;
fout<<“South Korea\n”;
fout.close(); //disconnect “country”
fout.open(“capital”); //connect “capital”
fout<<“Washington\n”;
fout<<“London\n”;
fout<<“Seoul\n”;
fout.close(); //disconnect “capital”
//Reading the files
const int N = 80; //size of line
char line[N];
ifstream fin; //create input stream
fin.open(“country”); //connect “country” to it
cout<<“contents of country file\n”;
while(fin) //chectk end-of-file
{
fin.getline(line, N); //read a line
cout<<line; //display it
}
fin.close(); //disconnect “country”
fin.open(“capital”);
cout<<“\nContents of capital file \n”; Output:
while (fin) Contents of country file
{ United States of America
United Kingdom
fin.getline(line, N); South Korea
cout<<line;
} Contents of country file
Washington
fin.close(); London
return 0; Seoul
}
Reading from two files
simultaneously
#include<iostream>
#include<fstream>
#include<stdlib>
using namespace std;
int main()
{
const int SIZE = 80;
char line[SIZE];
ifstream fin1, fin2;
fin1.open(“country”);
fin2.open(“capital”);
for(int i =1; i <= 10; i++)
{
if(fin1.eof()!=0)
{
cout<< “Exit from country \n”;
exit(1);
}
fin1.getline(line, SIZE);
cout << “Capital of ” << line;
if(fin2.eof()!=0)
{
cout << “Exit from capital\n”;
exit(1);
}
fin2.getline(line, SIZE);
cout <<line <<“\n”;
}
return 0;
}
Output:
Capital of United States of America
Washington
Capital of United Kingdom
London
Capital of South Korea
Seoul
Detecting end-of-file
• Detection of the end-of-file condition is necessary for preventing any
further attempt to read data from the file.
• In the following statement:
while (fin)
• An ifstream object, such as fin, returns a value of 0 if any error occurs
in the file operation including the end-of-file condition.
• There is another approach to detect the end-of-file condition, using
eof() member function.
• eof() is a member function of ios class which returns a non-zero value
if the end-of-file condition is encountered, and a zero otherwise.
File Pointers and their Manipulations
• Every file keeps track of two pointers, which are referred to as
get_pointer (in the input mode file) and put_pointer (in the output
mode file).
• These pointers indicate the current position in the file where reading
or writing will take place.
• These pointers make it possible to access files in a random order. That
means skipping the step where you move through the file in a specific
order and going straight to the location you want in the file.
The seekg(), seekp(), tellg(), and tellp() functions
• In C++, random access is achieved by manipulating the seekg(),
seekp(), tellg(), and tellp() functions.
• The seekg() and tellg() functions allow you to set and examine the
get_pointer, and the seekp() and tellp() functions perform these
operations on the put_pointer.
• The seekg() and tellg() functions are for input streams (ifstream), and
the seekp() and tellp() functions are for output streams (ofstream).
• However, if you use them with an fstream object, then tellg() and
tellp() return the same value. Also, seekg() and seekp() work the same
way in an fstream object.
• For example, the statement
infile.seekg(10);
moves the file pointer to the byte number 10. As the bytes in a file are
numbered beginning from zero, therefore, the pointer will be pointing
to the 11th byte in the file.
• Consider the following statements:
ofstream fileout;
fileout.open(“hello”, ios::app);
int p = fileout.tellp();
• On execution of these statements, the output pointer is moved to the
end of the file “hello” and the value of ‘p’ will represent the number
of bytes in the file.
• Specifying the offset
• ‘Seek’ functions seekg() and seekp() can also be used with two
arguments as follows:
seekg(offset, refposition);
seekp(offset, refposition);
• The parameter ‘offset’ represents the number of bytes the file pointer
is to be moved from the location specified by the parameter
‘refposition’. The ‘refposition’ takes one of the following three
constants defined in the ios class:
• ios:: beg start of the file
• ios::cur current position of the pointer
• ios::end end of the file
Sequential Input and Output
Operations
• The file stream classes support a number of member functions for
performing the input and output operations on files.
• put() and get() are designed for handling a single character at a time
whereas, write and read are designed to write and read blocks of
binary data.
put() and get() Functions
• The function put() writes a single character to the associated stream.
• Similarly, the function get() reads a single character from the
associated stream.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
char string[80];
cout<<“Enter a string \n”;
cin>> string;
int len = strlen(string);
fstream file; //input and output stream
file.open(“TEXT”, ios::in |ios::out);
for(int i=0; i<len; i++)
file.put(string[i]); //put a character to file
file.seekg(0); //go to the start
char ch;
while(file)
{
file.get(ch); //get a character from file
cout<<ch; //display it on screen
}
return 0;
}
//write() and read() Functions
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
const char *filename = “BINARY”;
int main()
{
float height[4] = {175.5, 153.0, 167.25, 160.70};
ofstream outfile;
outfile.open(filename);
outfile.write((char*) &height, sizeof(height));
outfile.close() //close the file for reading
for(int i=0; i<4; i++)
height[i] = 0;
ifstream infile;
infile.open(filename);
outfile.read((char*) &height, sizeof(height));
for(int i=0; i<4; i++)
{
cout.setf(ios::showpoint);
cout << setw(10) << setprecision(2)<< height[i];
}
infile.close()
return 0;
}
• The output of the above program would be:
175.50 153.00 167.25
Error Handling during File
Operations
• While working with file, following things may happen:
1. A file which we are attempting to open for reading does not exist.
2. The file name used for a new file may already exist.
3. We may attempt an invalid operation such as reading past the end-of-file.
4. There may not be any space in the disk for storing files.
5. We may use an invalid file name.
6. We may attempt to perform an operation when the file is not opened for that
purpose.
• The C++ file stream inherits a ‘stream-state’ member from the class ios
which records information on the status of the error conditions listed
above.
• The class ios supports several member functions that can be used to read
the status recorded in a file stream.
Function Return value and meaning
eof() Returns true (non-zero value) if end-of-file is encountered while
reading; otherwise returns false (zero)
fail() Returns true when an input or output operation has failed.
bad() Returns true if an invalid operation is attempted or any unrecoverable
error has occurred. However, if it is false, it may be possible to recover
from any other error reported, and continue operation.
good() Returns true if no error has occurred, this means, all the above
functions are false. For instance, if file.good() is true, all is well with the
stream file and we can proceed to perform I/O operations. When it
returns false, no further operations can be carried out.

• These functions may be used in the appropriate places in a


program to locate the status of a file stream and thereby take
necessary corrective measures.

You might also like