Tutorial: File Handling in C++

In this tutorial, our topic is: File handling in C++. Here we will learn the following things one by one.

  1. What are Headers in C++
  2. How to open and close a file
  3. How to write into a file in C++
  4. Read data from a file
  5. Some important operations on file handling in C++

Most of the C++ programs are only capable of Getting an Input and Showing an Output
But what if your program has to get something like Username and Password from the user?
We can’t be asking for the username password every time and hence we need to store it somewhere
This is where file handling is used

File Handling In C++

C++ has the functionality to open, read, write and close files.
An example of a file is a Text File(.txt)

If you know the basics of C++, this tutorial would be very easy for you. So let us begin talking about the important points

Headers

Along with the “iostream” header, we also import a header called “fstream”.
It is used for enabling the file handling function in C++
IOSTREAM = Input Output Stream. Similarly,
FSTREAM = File Stream

#include <iostream>
#include <fstream>

This package helps us use 3 new functions

  1. ofstream (Output File Stream): Used for basic Output functions and writing into a file
  2. ifstream (Input File Stream): Used for basic Input functions and reading from a file
  3. fstream (File Stream): Used for both writing and reading from a file

Along with these 3 functions, we also get 4 different operations we can use on a file

  1. open() : Used to Open a File
  2. read() : Used to Read the File
  3. write() : Used to Write data into the File
  4. close() : Used to Close the File

Opening/Closing a File in C++

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    fstream obj;
    obj.open("C:\File1212.txt",ios::out);
    if(!obj)
    {
        cout<<"File exists";
    }
    else
    {
        cout<<"file created";
        obj.close();
    }
    return 0;
}

This code is used to open a file.
But what if the file at that location does not exist?
The compiler automatically creates a new file over there with the name File1212 i.e. the name given to your file

Now let us address some important lines in the code

  1. “fstream obj”;  :
    Here we are creating an object “obj” that is used to refer to the function “fstream” we are using. It is basically a file pointer
  2. obj.open(“C:\File1212.txt”,ios::out);  :
    Here we are using the function “open” to tell the compiler to open the file at the location we are entering. The ios is used to tell the compiler what operation we would be performing on the file.
    It has 4 modes:
    1) ios::out  :  To use for file writing
    2) ios::in  :  To use for file inputting
    3) ios::app  :  To use for appending a file
    4) ios::trunc  :  To use for truncating a file
    5) ios::beg  :  To tell the beginning point of the file
    6)ios::cur  : To tell the current position of the pointer
    7)ios::end : To tell the endpoint of the file
  3. if(!obj)  :
    Here we are checking if the file already exists
  4. obj.close();  :
    If the file is opened, it’ll have to be closed too

Hence a file is created

Writing into a file in C++

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    fstream obj;
    obj.open("C:File.txt",ios::out);
    if(!obj)
    {
        cout<<"could not create file";
    }
    else
    {
        obj<<"Hello World";
        obj.close();
    }
    return 0;
}

If you notice carefully, there is only one line difference between the previous code and this code i.e.

obj<<“Hello World”

So basically we are writing hello world into the file that obj points to.
Do try this code with your preferred file location and file name. Then open that file and notice the text written out there

Reading from a File in C++

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    fstream obj;
    obj.open("C:File.txt",ios::in);
    if(!obj)
    {
        cout<<"could not create file";
    }
    else
    {
        char ch;
        while(!obj.eof())
        {
            obj>>ch;
            cout<<ch<<" ";
        }
        obj.close();
    }
    return 0;
}

You may learn: How to fetch a random line from a text file in C++

Again, this code is mostly similar to the previous codes except for a few lines
I have written “Testing” into the file and I am reading it and printing it with a space between each character.
Notice, we have used ios::in for reading

  1. while(!obj.eof())  :
    Here we are creating a loop that iterates the number of times a character is there.
    eof() basically means end of file. It is when the pointer reaches the point after the last character in the file
  2. obj>>ch;  :
    Here we are extracting a character and storing it in ch
  3. cout<<ch<<” “;  :
    Here we are printing the extracted character and printing it.

Hence the output would be:

T e s t i n g

Additional Operations on file handing

  1. tellp():
    Tells the current put pointer’s location
  2. tellg():
    Tells the current get pointer’s location
  3. seekp():
    Moves the put pointer to the desired location
  4. seekg():
    Moves the get pointer to the desired location
  5. put():
    Write a single line of character
  6. get():
    Read a single line of character

 

Hence we have covered file handling in C++.
I hope you understood the logic and were able to execute it by yourself. If you have any doubts regarding this, feel free to ask it in the comment section. Thank You.

Leave a Reply

Your email address will not be published. Required fields are marked *