Files - Cijin K Paul

advertisement
Files
Files are permanent storage areas while the variables we use in a program have only life only inside the
program. The inputs and output of a program can be written to a file for later usage. Also we can read
input from the files which are existing.
The classes used are ifstream , ofstream or fstream. As name indicates ifstream can have input
operations, ofstream can have output operations and fstream can have both input and output
operations. By default ifstream opens a file in input mode, ofstream opens the file in output mode and
the mode of fstream opening has to be specified.
Example 1:
ifstream in(“result”); -> opens a file named result which is available for reading.
Char *name,n1,n2;
in >>name ; -> reads the characters to the variable name till it finds space or enter
in.get(n1); reads the next character to n1
n2=in.get(); reads next character to n2.
The end of file can be checked using if(in.eof()!=0)
Example 2:
ofstream out(“result”); -> opens a file named result which is available for writing
char *name=”testing”,n1=’y’,n2=’n’;
out<<name ; writes the characters “testing” to the file result.
out.put(n1); writes character ‘y’ to file result
Example 3:
fstream f1(“result”,ios::app); opens the file in append mode, ie writing at end.
char *name=”testing”,n1=’y’,n2=’n’;
out<<name ; writes the characters “testing” to the file result.
out.put(n1); writes character ‘y’ to file result
The opening modes are
 ios::app -> append to end of file
 ios::ate -> At the end
 ios::binary -> binary file
 ios::in -> input mode
 ios::nocreate -> opens only existing files



ios::noreplace -> opens for writing if file exists
ios::out -> opens a file for writing
ios::trunk -> delete the contents of the file.
File Pointers
seekg() --- moves get pointer to a specified location
seekp()—moves put pointer to specified location
tellg() --- gives the current position of the get pointer
tellp()--- gives current position of the put pointer
Example : seekg (10,ios::beg) , moves pointer to the 10th byte starting from beginning.
The reference positions can be
ios::beg, ios::end, ios::cur
and the offset can be a number.
Download