The function open() can be used to open multiple files that uses the same stream object. For example to process a set of files sequentially,in such case a single stream object can be created and can be used to open each file in turn.
This can be done as follows;
File-stream-class stream-object;
stream-object.open (“filename”);
The following example shows how to work simultaneously with multiple files
WORKING WITH MULTIPLE FILES
//Creating files with open() function #include<iostream.h> #include<conio.h> #include<stdio.h> #include<stdlib.h> #include<fstream.h> int main() { ofstream fout; fout.open(“country”); fout<<”United states of America \n”; fout<<”United Kingdom”; fout<<”South korea”; fout.close(); fout.open(“capital”); fout<<”Washington\n”; fout<<”London\n”; fout<<”Seoul \n”; fout.close(); const int N =80; char line[N]; ifstream fin; fin.open(“country”); cout<<”contents of country file \n”; while (fin) { fin.getline(line,N); cout<<line; } fin.close(); fin.open(“capital”); cout<<”contents of capital file”; while(fin) { fin.getline(line,N); cout<<line; } fin.close(); return 0; }
Finding End of File
While reading a data from a file,it is necessary to find where the file ends i.e end of file.The programmer cannot predict the end of file,if the program does not detect end of file,the program drops in an infinite loop.To avoid this,it is necessary to provide correct instruction to the program that detects the end of file.Thus when end of file of file
is detected,the process of reading data can be easily terminated.
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.Thus the while loop terminates when fin returns a value of zero on reaching the end-of –file condition.
There is an another approach to detect the end of file condition.The statement
if(fin1.eof() !=0 )
{
exit(1);
}
returns a non zero value if end of file condition is encountered and zero otherwise.Therefore the above statement terminates the program on reaching the end of file.
File Opening Modes:
The ifstream and ofstream constructors and the function open() are used to open the files.Upto now a single arguments a single argument is used that is filename.However,these functions can take two arguments, the second one for specifying the file mode.
The general form of function open() with two arguments is:
stream-object.open(“filename”,mode);
The second argument mode specifies the purpose for which the file is opened.The prototype of these class member functions contain default values for second argument and therefore they use the default values in the absence of actual values.
The default values are as follows :
ios::in for ifstream functions meaning open for reading only.
ios::out for ofstream functions meaning open for writing only.
The file mode parameter can take one of such constants defined in class ios.The following table lists the file mode parameter and their meanings.
File Pointers and Manipulators
Each file has two pointers known as file pointers,one is called the input pointer and the other is called output pointer..The input pointer is used for reading the contents of of a given file location and the output pointer is used for writing to a given file location.Each time an input or output operation takes place,the appropriate pointer is automatically advanced.
Default actions
When a file is opened in read-only mode,the input pointer is automatically set at the beginning so that file can be read from the start.Similarly when a file is opened in write-only mode the existing contents are deleted and the output pointer is set at the beginning.This enables us to write the file from start.In case an existing file is to be opened in order to add more data,the file is opened in ‘append’ mode.This moves the pointer to the end of file.
Functions for Manipulations of File pointer:
All the actions on the file pointers takes place by default.
For controlling the movement of file pointers file stream classes support the following functions
seekg() Moves get pointer (input)to a specified location.
seekp() Moves put pointer (output) to a specified location.
tellg() Give the current position of the get pointer.
tellp() Give the current position of the put pointer.
For example, the statement
infile.seekg(10);
moves the pointer to the byte number 10.The bytes in a file are numbered beginning from zero.Therefore ,the pointer 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 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 file
- ios::cur Current position of the pointer
- ios::end End of file
The seekg() function moves the associated file’s ‘get’ pointer while the seekp() function moves the associated file’s ‘put ‘pointer.The following table shows some sample pointer offset calls and their actions.fout is an ofstream object.
Pointer offset calls Seek call Action
fout.seekg(o,ios::beg) Go to start
fout.seekg(o,ios::cur) Stay at the current position
fout.seekg(o,ios::end) Go to the end of file
fout.seekg(m,ios::beg) Move to (m+1)th byte in the file
fout.seekg(m,ios::cur) Go forward by m byte from current position
fout.seekg(-m,ios::cur) Go backward by m bytes from current position.
fout.seekg(-m,ios::end) Go backward by m bytes from the end
Sequential Input and Output Operations:
The file stream classes support a number of member functions for performing the input and output operations on files.One pairs of functions,put() and get() are designed for handling a single character at a time.Another pair of functions, write(),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.
The following program illustrates how the functions work on a file.The program requests for a string.On receiving the string,the program writes it,character by character,to the file using the put() function in a for loop.The length of string is used to terminate the for loop.
2 write() and read () functions:
The functions write() and read(),unlike the functions put() and get() ,handle the data in binary form.This means that the values are stored in the disk file in same format in which they are stored in the internal memory.An int character takes two bytes to store its value in the binary form,irrespective of its size.But a 4 digit int will take four bytes to store it in the character form.The binary input and output functions takes the following form:
infile.read (( char * ) & V,sizeof (V));
outfile.write (( char *) & V ,sizeof (V));
These functions take two arguments.The first is the address of the variable V, and the second is the length of that variable in bytes.The address of the variable must be cast to type char*(i.e pointer to character type)
Error Handling during File Operations:
There are many problems encountered while dealing with files like
- a file which we are attempting to open for reading does not exist.
- The file name used for a new file may already exist.
- We are attempting an invalid operation such as reading past the end of file.
- There may not be any space in the disk for storing more data.
- We may use invalid file name.
- 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.This member records information on the status of a file that is being currently used.
The stream state member uses bit fields to store the status of error conditions stated above.The class ios support 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 continues
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 is carried out.
These functions can be used at the appropriate places in a program to locate the status of a file stream and thereby to take the necessary corrective measures
The function clear() resets the error state so that further operations can be attempted