File Handling in C++





As you know, standard input and output operations are performed by using streams in C++.
So far, you have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively.

The operations on files are performed by using streams too.

  • C++ provides stream called fstream to perform read and write operations on files.

  • You have to include fstream to work with files.

  • C++ provides the following classes to perform operations on files:
    ofstream: Stream class to write on files
    ifstream: Stream class to read from files
    fstream: Stream class to both read and write from/to files.

Steps to Process a File in Program :

  1. Create an stream object (input or output or I/O) by declaring the stream to be appropriate class.
  2. Associate a file stream object that is open the file by using constructor or by using open() function.
  3. Process the file(read or write operations).
  4. Close the file by using close() function.

Opening a File :

  • A file must be open before performing operations(read/write).

  • Opening a file using constructor

    //for output
    ofstream  oFile("test.txt");
    
    //for input
    ifstream iFile("test.txt");
                                

  • Opening a file using open() function

    The first thing you need to work with file is to open it. Member function open( ) of fstream class opens file and associates a stream with it:

    Syntax

    
    void open (const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out);
                                    
    OR in short
    
    stream-object.open("fileName",mode);
                                    
    Here in above prototype:
    the first argument specifies the name or location of the file to be opened and
    the second argument is the mode in which the file will open

    File Opening Mode:

    ModeDescription
    ios::inOpen a file for reading
    ios::outOpen a file for writing
    ios::ate‘‘At end’’ (open and seek to the end)
    ios::appAppend mode.Append (i.e., add to the end of the file)
    ios::binaryOpen in binary mode.
    ios::truncDelete the contents of the file if it exist

    Each of the open member functions of classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument:

    ClassDefault Mode
    fstreamios::in | ios::out
    ofstreamios::out
    ifstreamios::in
    //for output
    ofstream oFile;
    oFile.open("test.txt");
    
    //for input
    ifstream iFile;
    iFile.open("test.txt");
                     

    The above statements of code opens a stream that is now associated with file “test.txt” from the folder where your source file is located.

    Note: If you try to call open() function for a stream, that is already associated with a file, cause an error.

    As mentioned above, a stream is associated with file. So, now you can perform the basic input/output (read/write) operations on file. It is done in the same way as you do with cin and cout objects.

  • You can combine two or more of these modes by ORing them together. For example if you want to open a file in write mode and want to truncate it in case it already exists.

    
     ofstream oFile;
     oFile.open("test.txt", ios::out | ios::trunc );                                
                                

Closing a File:

To close a file use close() function.
oFile.close();

iFile.close();

Writing to a File:

Instead of using cout object ,just use an ofstream or fstream object to write (output) on file.


Reading from a File:

Instead of using cin object ,just use an ifstream or fstream object to read (input) from file.

Example: Program to Read/Write on Files:
#include<iostream>
#include<fstream>
using namespace std;
 
int main () 
{
 string str;

// open a file in write mode.
 ofstream oFile;
 oFile.open("test.txt");

 cout << "Writing to the file" << endl;
 cout << "Enter your name: "; 
 getline(cin,str);

// write inputted data into the file.
 oFile<< str << endl;

 cout<< "Enter your age: "; 
 cin >> str;
 cin.ignore();
   
// again write inputted data into the file.
 oFile<< str << endl;

// close the opened file.
 oFile.close();

// open a file in read mode.
 ifstream inFile; 
 inFile.open("test.txt"); 
 
 cout<< "Reading from the file" << endl; 
 while(getline(inFile, str))
  {
 // write the data at the screen.
    cout << str << endl;
  }
   
 // close the opened file.
 inFile.close();

 return 0;
}                    
When the above code is compiled and executed, it produces the following sample input and output:
OUTPUT:
Writing to the file
Enter your name: ProwessApps
Enter your age: 20
Reading from the file
ProwessApps
20                   

is_open():

Before performing any operation (read/write) we must check that file is open or not. To ensure that file is open or not successfully, you can call a member function is_open().
This function returns a boolean value (true/false). This function returns true if the file is opened and associated with this stream. Otherwise, it returns false:

Example:
#include<iostream>
#include<fstream>
using namespace std;
 
int main () 
{
// open a file in read mode.
 ifstream inFile; 
 inFile.open("test.txt"); 
 if(inFile.is_open())
  {
    cout<<"File Opened Successfully";
  }
  else
  {
    cout<<"File doesn't exist!";
  }
 
 // close the opened file.
   inFile.close();

   return 0;
}                  

When the above code is compiled and executed, it may produces the following output:
1. If file opened: File Opened Successfully
2. If file not-opened: File doesn't exist!

So, its a very handy function, you should use it before performing any operation to the file.


put() and get() function:

The function put() writes a single character to the associated stream.

The function get() reads a single character form the associated stream.

Example:
stream-object.get(ch);
stream-object.put(ch);
Program to read/write data from/to file character by character:
#include<fstream>
#include<iostream>
using namespace std;
 
int main () 
{
 char ch;;
//open a file in write mode.
 ofstream oFile;
 oFile.open("test.txt");

 cout<<"Enter data to Write on the file";
 cout<< endl; 
 cout<<"Enter '@' to stop writing:";
 cout<< endl;
   
//write inputted data into the file.
 cin>>ch;
 while(ch!='@'){
     oFile.put(ch);
     cin>>ch;
   }
      

// close the opened file.
  oFile.close();

// open a file in read mode.
 ifstream inFile; 
 inFile.open("test.txt"); 
 
 cout<<"Reading from the file:";
 cout<< endl;
 while(!inFile.eof())
  {
   inFile.get(ch);
   cout<< ch;
  }

 // close the opened file.
 inFile.close();

 return 0;
}                   
OUTPUT:
Enter data to Write on the file
Enter '@' to stop writing:
H
E
L
L
O
@
Reading from the file:
HELLO               


Stream Positioning Pointers:

  • All I/O streams objects have, at least, one internal stream pointer:

  • ifstream, like istream, keeps an internal get position with the location of the element to be read in the next input operation.

  • ofstream, like ostream, keeps an internal put position with the location where the next element has to be written.

  • Finally, fstream, keeps both, the get and the put position, like iostream.

  • These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions:

    FunctionDescription
    seekg(int, point)is used to move the get pointer to a desired location with respect to a reference point.
    seekp(int, point)is used to move the put pointer to a desired location with respect to a reference point.
    tellg()is used to know where the get pointer is in a file.
    tellp()is used to know where the put pointer is in a file.
  • The argument to seekg and seekp normally is a long integer that represent the number of bytes to move and the second argument can be specified to indicate the seek direction.

  • The seek direction can be:

    ios::beg ( the default ) for positioning relative to the beginning of a stream.
    ios::cur for positioning relative to the current position in a stream.
    ios::end for positioning relative to the end of a stream.
    Example: for example you want to read data after 5 bytes from beginning of file then you will write:
        iFile.seekg(5,ios::beg);

    you want to read data 5 bytes from end of file then you will write:
        iFile.seekg(-5,ios::end);

Next topic is Exception Handling





 








Training For College Campus

We offers college campus training for all streams like CS, IT, ECE, Mechanical, Civil etc. on different technologies like
C, C++, Data Structure, Core Java, Advance Java, Struts Framework, Hibernate, Python, Android, Big-Data, Ebedded & Robotics etc.

Please mail your requirement at info@prowessapps.in


Projects For Students

Students can contact us for their projects on different technologies Core Java, Advance Java, Android etc.

Students can mail requirement at info@prowessapps.in


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved