Signup/Sign In

File Handling using File Streams in C++

File represents storage medium for storing data or information. Streams refer to sequence of bytes. In Files we store data i.e. text or binary data permanently and use these data to read or write in the form of input output operations by transferring bytes of data. So we use the term File Streams/File handling. We use the header file <fstream>

  • ofstream: It represents output Stream and this is used for writing in files.
  • ifstream: It represents input Stream and this is used for reading from files.
  • fstream: It represents both output Stream and input Stream. So it can read from files and write to files.

Operations in File Handling:

  • Creating a file: open()
  • Reading data: read()
  • Writing new data: write()
  • Closing a file: close()

Creating/Opening a File

We create/open a file by specifying new path of the file and mode of operation. Operations can be reading, writing, appending and truncating. Syntax for file creation: FilePointer.open("Path",ios::mode);

  • Example of file opened for writing: st.open("E:\studytonight.txt",ios::out);
  • Example of file opened for reading: st.open("E:\studytonight.txt",ios::in);
  • Example of file opened for appending: st.open("E:\studytonight.txt",ios::app);
  • Example of file opened for truncating: st.open("E:\studytonight.txt",ios::trunc);
#include<iostream>
#include<conio>
#include <fstream>

using namespace std;

int main()
{
    fstream st; // Step 1: Creating object of fstream class
    st.open("E:\studytonight.txt",ios::out);  // Step 2: Creating new file
    if(!st) // Step 3: Checking whether file exist
    {
        cout<<"File creation failed";
    }
    else
    {
        cout<<"New file created";
        st.close(); // Step 4: Closing file
    }
    getch();
    return 0;
}

Writing to a File

#include <iostream>
#include<conio>
#include <fstream>

using namespace std;

int main()
{
    fstream st; // Step 1: Creating object of fstream class
    st.open("E:\studytonight.txt",ios::out);  // Step 2: Creating new file
    if(!st) // Step 3: Checking whether file exist
    {
        cout<<"File creation failed";
    }
    else
    {
        cout<<"New file created";
        st<<"Hello";    // Step 4: Writing to file
        st.close(); // Step 5: Closing file
    }
    getch();
    return 0;
}

Here we are sending output to a file. So, we use ios::out. As given in the program, information typed inside the quotes after "FilePointer <<" will be passed to output file.


Reading from a File

#include <iostream>
#include<conio>
#include <fstream>

using namespace std;

int main()
{
    fstream st; // step 1: Creating object of fstream class
    st.open("E:\studytonight.txt",ios::in);   // Step 2: Creating new file
    if(!st) // Step 3: Checking whether file exist
    {
        cout<<"No such file";
    }
    else
    {
        char ch;
        while (!st.eof())
        {
            st >>ch;  // Step 4: Reading from file
            cout << ch;   // Message Read from file
        }
        st.close(); // Step 5: Closing file
    }
    getch();
    return 0;
}

Here we are reading input from a file. So, we use ios::in. As given in the program, information from the output file is obtained with the help of following syntax "FilePointer >>variable".


Close a File

It is done by FilePointer.close().

#include <iostream>
#include<conio>
#include <fstream>

using namespace std;

int main()
{
    fstream st; // Step 1: Creating object of fstream class
    st.open("E:\studytonight.txt",ios::out);  // Step 2: Creating new file
    st.close(); // Step 4: Closing file
    getch();
    return 0;
}

Special operations in a File

There are few important functions to be used with file streams like:

  • tellp() - It tells the current position of the put pointer.

    Syntax: filepointer.tellp()

  • tellg() - It tells the current position of the get pointer.

    Syntax: filepointer.tellg()

  • seekp() - It moves the put pointer to mentioned location.

    Syntax: filepointer.seekp(no of bytes,reference mode)

  • seekg() - It moves get pointer(input) to a specified location.

    Syntax: filepointer.seekg((no of bytes,reference point)

  • put() - It writes a single character to file.
  • get() - It reads a single character from file.

Note: For seekp and seekg three reference points are passed:
ios::beg - beginning of the file
ios::cur - current position in the file
ios::end - end of the file

Below is a program to show importance of tellp, tellg, seekp and seekg:

#include <iostream>
#include<conio>
#include <fstream>

using namespace std;

int main()
{
    fstream st; // Creating object of fstream class
    st.open("E:\studytonight.txt",ios::out);  // Creating new file
    if(!st) // Checking whether file exist
    {
        cout<<"File creation failed";
    }
    else
    {
        cout<<"New file created"<<endl;
        st<<"Hello Friends"; //Writing to file
        
        // Checking the file pointer position
        cout<<"File Pointer Position is "<<st.tellp()<<endl;  
        
        st.seekp(-1, ios::cur); // Go one position back from current position
        
        //Checking the file pointer position
        cout<<"As per tellp File Pointer Position is "<<st.tellp()<<endl; 
        
        st.close(); // closing file
    }
    st.open("E:\studytonight.txt",ios::in);   // Opening file in read mode
    if(!st) //Checking whether file exist
    {
        cout<<"No such file";
    }
    else
    {
        char ch;
        st.seekg(5, ios::beg);  // Go to position 5 from begning.
        cout<<"As per tellg File Pointer Position is "<<st.tellg()<<endl; //Checking file pointer position
        cout<<endl;
        st.seekg(1, ios::cur); //Go to position 1 from beginning.
        cout<<"As per tellg File Pointer Position is "<<st.tellg()<<endl; //Checking file pointer position
        st.close(); //Closing file
    }
    getch();
    return 0;
}

New file created File Pointer Position is 13 As per tellp File Pointer Position is 12 As per tellg File Pointer Position is 5 As per tellg File Pointer Position is 6