File Handling in C

++
By: Haya Majid Qureshi BS(CS)-II

Introduction
‡ Computer programs are associated to work with files as it helps in storing data & information permanently. ‡ File - itself a bunch of bytes stored on some storage devices. ‡ The library predefine a set of operations for all file related handling through certain classes.

In another words. i.  File Program ( Input stream) .e cin and cout.C++ STREAMS ‡ A stream is general name given to the flow of data. ‡ In C++ a stream is represented by an object of a particular class .reads-extract  Program File (Output stream) ± write-insert .

FLOW OF DATA DATA Program Input Stream >> (Extraction operator) Output Stream << (Insertion Operator) Files istream class DATA ostream class .

ACCESS TO FILE I/O ‡ ifstream ‡ ofstream ‡ fstream .

The Stream Class Hierarchy ios Istream Get() Read() >> iostream Ostream Put() Write() << fstream Ifstream Open() Tellg() Seekg() Ofstream Open() Tellp() Seekp() fstreambase .

File Handling Hierarchy .

DIFFERENT FILE OPERATION ‡ ‡ ‡ ‡ ‡ OPENING A FILE CLOSING A FILE READING FROM A FILE WRITING ON A FILE CHECKING FOR END OF FILE .

This method is used when we want to manage multiple files. . A file can be opened in two ways: ‡ Using the constructor function of the class. This method is useful when we open only one file in the stream. ‡ Using the member function open() of the class. we must first create a file stream and than link it to the filename.OPENING A FILE ‡ For opening a file.

Mode is an optional parameter with a combination of the following flags: . filename ± file to open (full path or local) mode ± how to open (1 or more of following -using I). mode).USING MEMBER FUNCTION ‡ In order to open a file with a stream object we use its member function open(): open (³const char*filename´.

myfile.bin".Contd  ios::left ± left-adjust output  ios::right ± right-adjust output  ios::in / ios::out ± (the defaults of ifstream and ofstream)  ios:nocreate / ios::noreplace ± open only if the file exists / doesn¶t exist  ios::trunc ± open an empty file  ios::binary ± open a binary file (default is textual) Example : ofstream myfile. .open ("example. ios::out | ios::trunc |ios::in).

close(). myfile.USING CONSTRUCTOR ‡ A constructor that automatically calls the open() member function and has the exact same parameters as this member. ‡ operation in our previous example by writing: ofstream myfile ("example.bin". ‡ To close the file using the method ³close()´. . ios::out | ios::app | ios::binary).

with the only difference that we have to associate these streams with physical files. .Contd ± we can use our file streams the same way we are already used to use cin and cout.

myfile << "Writing this to a file.close().\n". myfile. } .open ("example. myfile. return 0.Example #include <iostream> #include <fstream> void main () { ofstream myfile.txt").

dat"). out_stream.fail()) { cout << "Input file open failed\n".open("outfile.1: To access file handling routines: #include <fstream. 3: To connect your program's variable (its internal name) to an external file in_stream. 4: To see if the file opened successfully: if (in_stream.open("infile. } .h> 2: To declare variables that can be used to access file: ifstream in_stream.dat"). ofstream out_stream.

out_stream.. must declare a variable to hold the data and then read it using the extraction operator: int num..] NOTE: Streams are sequential ± data is read and written in order . in_stream >> num.close(). 5: To get data from a file (one option). . [Compare: cin >> num. use insertion operator: out_stream << num.] 6: To put data into a file.close(). [Compare: cout << num. 7: When done with the file: in_stream.

For instance: eof() ²end of file character.status of file at opening for I/O. file stream classes inherit a stream state member from the ios class. fail().Stream State Member Function ‡ In C++. bad()-invalid file operations or unrecoverable error . which gives out the information regarding the status of the stream. . good()-previous file operation has been successful.

TYPES OF FILES ‡ The two basic types are: ± TEXT ± BINARY .

but with the text file we will use the usual input operator(>>). . ‡ A binary file stores data to disk in the same form in which it is represented in main memory. ‡ For the binary file we will use write to write to the file.Contd ‡ A text file consists of readable characters . ‡ With the binary file we will use the read function to read record. whereas for the text file we will use the usual output operator(<<).

Reading and Writing to Binary files ‡ File streams include two member functions specifically designed to input and output binary data sequentially: write and read. read ( memory _ block. size ). write ( memory _ block. size ). . ‡ The first one (write) is a member function of ostream inherited by ofstream. ‡ And read is a member function of istream that is inherited by ifstream.

put(ch). ‡ To read: ± get() ± reading a single character .get(ch). outfile. ± getline() ± reading a single line. infile. .Character I/O ‡ To write: ± put() ± writing single character.

‡ By default reading pointer is set at the beginning and writing pointer is set at the end (when you open file in ios::app mode) .Stream Pointer ‡ All i/o file maintains atleast one internal pointers: get _ pointer and put _ pointer ‡ They enable to attain the random access in file otherwise which is sequential in nature.

allow you to set and examine the ‡ get stream pointer (in the case of tellg) ‡ put stream pointer (in the case of tellp).FUNCTION ASSOCIATED WITH FILE POINTER ‡ tellg() and tellp() ‡ These two member functions have no parameters. ‡ return a value of an integer data type representing the current position. .

. Moves the file pointer to the byte number 10. The bytes in a file are numbered beginning from zero. The first prototype is: seekg ( position ). the pointer will be pointing to the 11th byte in the file. Thus. infile.Moves put pointer (output) to a specified location.Contd ‡ seekg() and seekp() Both functions are overloaded with two different prototypes.seekg(10).Moves get pointer (input) to a specified location. seekp ( position ).

direction ). The parameter offset represents the number of bytes. The parameter direction specified the location. direction ). . seekp ( offset.Contd ‡ The other prototype for these functions is: seekg ( offset. The direction takes one of the following these constant defined in the ios class.

Contd ‡ ios::beg (counted from the beginning of the stream) ‡ ios::cur (counted from the current position of the stream) ‡ ios::end(counted from the end of the stream) .

seekg (0. begin = myfile.tellg().close(). myfile.\n". } . cout << "size is: " << (end-begin) << " bytes. myfile.tellg().end.Example // obtaining file size #include <iostream> #include <fstream> int main () { long begin. ios::end). end = myfile. return 0. ifstream myfile ("example.txt").

// for read while (! in_stream.eof()) {loop body in _ stream >> num.EOF and File I/O within Function ‡ When using a file within a function. EOF is automatically included in text files we create. We use the end-of-file (EOF) to accomplish this. it is often desirable to process some unknown amount of data. ‡ As with keyboard input. in _ stream >> num.} . the file parameter must be a reference parameter: int read_file(ifstream& infile).