Basic File Processing Operations

ofstream : This data type represents the output file stream and is used to create files and to write information to files.

ifstream : This data type represents the input file stream and is used to read information from files.

fstream : This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream.

Note : To perform file processing in C++, header files and must be included in your C++ source file.


opening a file in c++

                     void open(const char *filename, ios::openmode mode);
    

const char *filename : specifies the name and location of the file to be opened.

ios::openmode mode: defines the mode in which the file should be opened.

Mode Description
ios::app Append mode. All output to that file to be appended to the end.
ios::ate Open a file for output and move the read/write control to the end of the file.
ios::in Open a file for reading.
ios::out Open a file for writing.
ios::trunc If the file already exists, its contents will be truncated before opening the file.

Note : You can combine two or more of these values by OR operator.

outfile.open("file.dat", ios::out | ios::in );
    

closing a file in c++

fileName.close()
    

When a C++ program terminates it automatically closes flushes all the streams,. But it is always a good practice that a programmer should close all the opened files before program termination.


Reading and Writing in c++

the following c++ program opens a file in a reading and writing mode.

  
    #include <fstream>  
    #include  
    <iostream>  
    
    using namespace std;  
    
    int main (){  
      char name[100];  
      int age;  
      
      // open a file in write mode.  
      ofstream outfile;  
      outfile.open("afile.txt", ios::app);  
      cout << "Writing to the file" << endl;
      cout<<"Enter your name: ";
      cin-getline(name, 100);  
      
      // write name into the file.
      outfile <<< name << endl;  
      
      cout<<"Enter your age: ";
      cin >> age; 
       
      // again write age into the file.
      outfile <<< age << endl;  
      
      // close the opened file.
      outfile.close();
      
      return 0;
    }
    

Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg for istream and seekp for ostream.

The seek direction can be:

Some examples of positioning the “get” file-position pointer are:

// position to the n_th byte of fileObject (assumes ios::beg)
    fileObject.seekg( n );
    
    // position n bytes forward in fileObject  
    fileObject.seekg( n, ios::cur );  
    
    // position n bytes back from end of fileObject
    ileObject.seekg( n, ios::end );  
    
    // position at end of fileObject
    fileObject.seekg( 0, ios::end );