Reading file in c++
Reading a file in c and c++ are different. In c we will use the file pointer and in c++ we use the streams.
Initializing object for file:
The file object can be intialzed by the following way
The first form just creates the object where as the second form creates the object as well as open the file with input operation mode.
Opening a file manually:
You can also open the file manually by calling the member function open.
C++ supports both the formats. If mode is not passed then the default mode is applied
More than one mode can be passed by using the pipe symbol.
Read a file using a overloaded operator <<
The << operator is overloaded to read a file.
This system reads the file line by line. You can use eof() function to check whether the system read the entire file.
Here the buffer can be a char array and also a string class object.
Beaware of getline function here. There are two getline functions. Function which is defined under the string class and another function is defined under the istream class. Both takes the different set of parameter.
getline() under string class
getline() under the istream class
Read() method of istream:
The read method reads the n number of character in the stream.
Its stores the result in the char array
Manipulation on file position:
use the seekg function to move beween the various positions of file. seekg is the member function of istream.
The first function moves the file pointer to the particular file position. whereas the second function goes to the certain position based on the offset set. The second parameter decides from where it should start. The various value can be set to way is ios_base::beg, ios_base::cur, ios_base::end.
seekg doesnot work when the end of file flag is set. At such cased you need to call the clear method to reset the flags.
clear() method of istream:
The clear reset the eofflag. Calling clear function doesnot make file pointer to move to the beginning of file.
File pointer postion:
The tellg returns the file pointer position. Return type is streampos but you type cast it to integer. tellg will work even if eofbit flag is set. tellg is the member function of istream class.
Here the ‘g’ in tellg represents the get and ‘p’ in tellp represents the put.
Number of characters read gcount:
The gcount returns the number of characters read at last time.
The gcount is the member function of istream class.
Ignore the content up to some delimiter:
This will ignore the content of file up to the delimiter and the n represent the maximum no of limit to go. By default both the values are set to 1 and EOF.
Write a content to file:
This will write the content to file poited by ostream object.