Categories: C++

File Handling using File Streams in C++

  • A file is a medium for storing data or information. The sequence of bytes provided as input to the executing program and the sequence of bytes returned by the executing program is referred to as streams.
  • File handling is the process of storing data permanently in a computer. We can store data in secondary memory by using file handling (Hard disk).
Classes for File stream operations :

We will use the header file <fstream> which defines three new data types:

  • ofstream: This data type represents the output file stream and is used to create and write data to files.
  • ifstream: This data type is used to read information from files and represents the input file stream.
  • fstream: This data type represents the file stream in general, and it possesses the capabilities of both ofstream and ifstream, which means it can create files, write data to files, and read data from files.
Operations in File Handling:
  • Creating/Opening a file: open()
  • Reading data: read()
  • Writing new data: write()
  • Closing a file: close()
Creating/Opening a File:

Before you can read from or write to a file, it must first be opened. To open a file for writing, use either ofstream or fstream. And the ifstream object is used to open a file solely for reading purposes.

We create/open a file by specifying the file’s new path and mode of operation.

File creation syntax:

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

for instance:

FilePointer.open("Path",ios::mode);

Mode Flag:

Mode FlagDescription
ios::appAppend mode. All output to that file is to be appended to the end.
ios::ateOpen a file for output and move the read/write control to the end of the file.
ios::inOpen a file for reading.
ios::outOpen a file for writing.
ios::truncIf the file already exists, its contents will be truncated before opening the file.
Example:
#include<iostream>
#include<conio>
#include <fstream>

using namespace std;

int main()
{
    fstream st; //Creating object of fstream class
    st.open("C:\File1.txt",ios::out);  // Creating new file
    if(!st) // Checking whether file exist
    {
        cout<<"File creation failed";
    }
    else
    {
        cout<<"New file created";
        st.close(); // Closing file
    }
    getch();
    return 0;
}
Reading data from a file:

The stream extraction operator (>>) is used to read data from a file into our program, just as it is used to input data from the keyboard. The only difference is that instead of the cin object, we use an ifstream or fstream object.

Example:
#include <iostream>
#include<conio>
#include <fstream>

using namespace std;

int main()
{
    fstream st; // Creating object of fstream class
    st.open("C:\File1.txt",ios::in);   // Creating new file
    if(!st) // Checking whether file exist
    {
        cout<<"No such file";
    }
    else
    {
        char ch;
        while (!st.eof())
        {
            st >>ch;  // Reading from file
            cout << ch;   // Message Read from file
        }
        st.close(); // Closing file
    }
    getch();
    return 0;
}
Writing to a File:

In C++ programming, we use the stream insertion operator (<<) to write information to a file from your program, just as we use that operator to output information to the screen. The only difference is that instead of the cout object, we use an ofstream or fstream object.

Example:
#include <iostream>
#include<conio>
#include <fstream>

using namespace std;

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

It is done by FilePointer.close(). Just the way we did in the previous examples.

 st.close(); // Closing file
File Position Pointers & Operations:

There are a few important functions that can be used with file streams:

seekg( ):

  • position to the nth byte of fileObject (assumes ios::beg) i.e, fileObject.seekg( n );
  • position n bytes forward in fileObject i.e, fileObject.seekg( n, ios::cur );
  • position n bytes back from the end of fileObject i.e, fileObject.seekg( n, ios::end );
  • position at end of fileObject i.e, fileObject.seekg( 0, ios::end );

seekp():

  • moves the put pointer to mentioned location i.e, fileObject.seekp(no of bytes, reference mode)

tellp():

  • tells the current position of the put pointer, i.e, fileObject.tellp()

tellg():

  • tells the current position of the get pointer, i.e, fileObject.tellg()

Note: also read about Exception Handling in C++

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago