The Wayback Machine - https://web.archive.org/web/20240708182153/https://www.geeksforgeeks.org/file-handling-c-classes/
Open In App

File Handling through C++ Classes

Last Updated : 18 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

File handling is used to store data permanently in a computer. Using file handling we can store our data in secondary memory (Hard disk).
How to achieve the File Handling
For achieving file handling we need to follow the following steps:-
 STEP 1-Naming a file
 STEP 2-Opening a file
 STEP 3-Writing data into the file
 STEP 4-Reading data from the file
 STEP 5-Closing a file.

Streams in C++ :-

We give input to the executing program and the execution program gives back the output. The sequence of bytes given as input to the executing program and the sequence of bytes that comes as output from the executing program are called stream. In other words, streams are nothing but the flow of data in a sequence.

The input and output operation between the executing program and the devices like keyboard and monitor are known as “console I/O operation”. The input and output operation between the executing program and files are known as “disk I/O operation”.

Classes for File stream operations :-

The I/O system of C++ contains a set of classes which define the file handling methods. These include ifstream, ofstream and fstream classes. These classes are derived from fstream and from the corresponding iostream class. These classes, designed to manage the disk files, are declared in fstream and therefore we must include this file in any program that uses files.
1. ios:-

  • ios stands for input output stream.
  • This class is the base class for other classes in this class hierarchy.
  • This class contains the necessary facilities that are used by all the other derived classes for input and output operations.

2. istream:-

  • istream stands for input stream.
  • This class is derived from the class ‘ios’.
  • This class handle input stream.
  • The extraction operator(>>) is overloaded in this class to handle input streams from files to the program execution.
  • This class declares input functions such as get(), getline() and read().
     

3. ostream:-

  • ostream stands for output stream.
  • This class is derived from the class ‘ios’.
  • This class handle output stream.
  • The insertion operator(<<) is overloaded in this class to handle output streams to files from the program execution.
  • This class declares output functions such as put() and write().

4. streambuf:-

  • This class contains a pointer which points to the buffer which is used to manage the input and output streams.

5. fstreambase:-

  • This class provides operations common to the file streams. Serves as a base for fstream, ifstream and ofstream class. 
  • This class contains open() and close() function.

6. ifstream:-

  • This class provides input operations.
  • It contains open() function with default input mode. 
  • Inherits the functions get(), getline(), read(), seekg() and tellg() functions from the istream.

7. ofstream:-

  • This class provides output operations.
  • It contains open() function with default output mode. 
  • Inherits the functions put(),  write(), seekp() and tellp() functions from the ostream.

8. fstream:-

  • This class provides support for simultaneous input and output operations.
  • Inherits all the functions from istream and ostream classes through iostream.

9. filebuf:-

  • Its purpose is to set the file buffers to read and write.
  • We can also use file buffer member function to determine the length of the file.
     

In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in fstream headerfile. 
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. 

Now the first step to open the particular file for read or write operation. We can open file by 
1. passing file name in constructor at the time of object creation 
2. using the open method 

For e.g.  

Open File by using constructor 
ifstream (const char* filename, ios_base::openmode mode = ios_base::in); 
ifstream fin(filename, openmode) by default openmode = ios::in 
ifstream fin(“filename”);

Open File by using open method 
Calling of default constructor 
ifstream fin;
fin.open(filename, openmode) 
fin.open(“filename”); 
 

Modes :  

Member Constant Stands For Access
in * input File open for reading: the internal stream buffer supports input operations.
out output File open for writing: the internal stream buffer supports output operations.
binary binary Operations are performed in binary mode rather than text.
ate at end The output position starts at the end of the file.
app append All output operations happen at the end of the file, appending to its existing contents.
trunc truncate Any contents that existed in the file before it is open are discarded.

Default Open Modes :  

ifstream ios::in
ofstream ios::out
fstream ios::in | ios::out

Problem Statement : To read and write a File in C++. 
Examples: 

Input : 
Welcome in GeeksforGeeks. Best way to learn things.
-1
Output : 
Welcome in GeeksforGeeks. Best way to learn things.

Below is the implementation by using ifstream & ofstream classes.  

C++




/* File Handling with C++ using ifstream & ofstream class object*/
/* To write the Content in File*/
/* Then to read the content of file*/
#include <iostream>
 
/* fstream header file for ifstream, ofstream,
  fstream classes */
#include <fstream>
 
using namespace std;
 
// Driver Code
int main()
{
    // Creation of ofstream class object
    ofstream fout;
 
    string line;
 
    // by default ios::out mode, automatically deletes
    // the content of file. To append the content, open in ios:app
    // fout.open("sample.txt", ios::app)
    fout.open("sample.txt");
 
    // Execute a loop If file successfully opened
    while (fout) {
 
        // Read a Line from standard input
        getline(cin, line);
 
        // Press -1 to exit
        if (line == "-1")
            break;
 
        // Write line in file
        fout << line << endl;
    }
 
    // Close the File
    fout.close();
 
    // Creation of ifstream class object to read the file
    ifstream fin;
 
    // by default open mode = ios::in mode
    fin.open("sample.txt");
 
    // Execute a loop until EOF (End of File)
    while (getline(fin, line)) {
       
        // Print line (read from file) in Console
        cout << line << endl;
    }
 
    // Close the file
    fin.close();
 
    return 0;
}


Time Complexity: O(n)
Auxiliary Space: O(1)

Below is the implementation by using fstream class. 

C++




/* File Handling with C++ using fstream class object */
/* To write the Content in File */
/* Then to read the content of file*/
#include <iostream>
 
/* fstream header file for ifstream, ofstream,
   fstream classes */
#include <fstream>
 
using namespace std;
 
// Driver Code
int main()
{
    // Creation of fstream class object
    fstream fio;
 
    string line;
 
    // by default openmode = ios::in|ios::out mode
    // Automatically overwrites the content of file, To append
    // the content, open in ios:app
    // fio.open("sample.txt", ios::in|ios::out|ios::app)
    // ios::trunc mode delete all content before open
    fio.open("sample.txt", ios::trunc | ios::out | ios::in);
 
    // Execute a loop If file successfully Opened
    while (fio) {
 
        // Read a Line from standard input
        getline(cin, line);
 
        // Press -1 to exit
        if (line == "-1")
            break;
 
        // Write line in file
        fio << line << endl;
    }
 
    // Execute a loop until EOF (End of File)
    // point read pointer at beginning of file
    fio.seekg(0, ios::beg);
 
    while (fio) {
 
        // Read a Line from File
        getline(fio, line);
 
        // Print line in Console
        cout << line << endl;
    }
 
    // Close the file
    fio.close();
 
    return 0;
}


Time Complexity: O(n)
Auxiliary Space: O(1)

C++




Q: write a single file handling program in c++ to reading and writing data on a file.
 
#include<iostream>
#include<fstream>
   
using namespace std;
main()
{
      int rno,fee;
      char name[50];
   
      cout<<"Enter the Roll Number:";
      cin>>rno;
       
      cout<<"\nEnter the Name:";
      cin>>name;
       
      cout<<"\nEnter the Fee:";
      cin>>fee;
   
      ofstream fout("d:/student.doc");
   
      fout<<rno<<"\t"<<name<<"\t"<<fee;   //write data to the file student
   
      fout.close();
   
      ifstream fin("d:/student.doc");
   
      fin>>rno>>name>>fee;   //read data from the file student
   
      fin.close();
   
      cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
   
    return 0;   
}


Time Complexity: O(1)
Auxiliary Space: O(1)

C++




// Q: WA C++ file handling program to read data from the file called student.doc
 
#include<iostream>
#include<fstream>
 
using namespace std;
 
main()
{
      int rno,fee;
      char name[50];
   
      ifstream fin("d:/student.doc");
   
      fin>>rno>>name>>fee;   //read data from the file student
   
      fin.close();
   
      cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
  
      return 0;   
}


Time Complexity: O(1)
Auxiliary Space: O(50)



Previous Article
Next Article

Similar Reads

ATM using file handling in C++
In this article, the task is to implement an ATM with functions like add, delete, search, and update users using file handling in C++. File handling: File handling is used to store the output of a program in a file.In C++, files use three classes fstream, ifstream, ofstream available in fstream header file for file handling. Some Important Instruct
6 min read
Four File Handling Hacks which every C/C++ Programmer should know
We will discuss about four file hacks listed as below- Rename - Rename a file using C/C++Remove – Remove a file using C/C++File Size - Get the file size using C/C++Check existence – Check whether a file exists or not in C/C++ C/C++ Code // C++ Program to demonstrate the // four file hacks every C/C++ must know // Note that we are assuming that the
3 min read
Set Position with seekg() in C++ File Handling
seekg() is a function in the iostream library that allows you to seek an arbitrary position in a file. It is included in the &lt;fstream&gt; header file and is defined for istream class. It is used in file handling to sets the position of the next character to be extracted from the input stream from a given file. Syntax: There are two syntaxes for
3 min read
tellp() in file handling with c++ with example
The tellp() function is used with output streams, and returns the current "put" position of the pointer in the stream. It has no parameters and return a value of the member type pos_type, which is an integer data type representing the current position of the put stream pointer.Syntax: pos_type tellp(); Return - Current output position indicator on
2 min read
PHP | Basics of File Handling
File handling is needed for any application. For some tasks to be done file needs to be processed. File handling in PHP is similar as file handling is done by using any programming language like C. PHP has many functions to work with normal files. Those functions are: 1) fopen() - PHP fopen() function is used to open a file. First parameter of fope
2 min read
Difference Between C++ Text File and Binary File
A text file is the one in which data is stored in the form of ASCII characters and is normally used for storing a stream of characters. Text files are organized around lines, each of which ends with a newline character ('\n'). The source code files are themselves text files. A binary file is the one in which data is stored in the file in the same w
4 min read
C program to copy contents of one file to another file
[GFGTABS] C #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; // For exit() int main() { FILE *fptr1, *fptr2; char filename[100]; int c; printf(&quot;Enter the filename to open for reading: &quot;); scanf(&quot;%s&quot;, filename); // Open one file for reading fptr1 = fopen(filename, &quot;r&quot;); if (fptr1 == NULL) { printf(&quot;Cannot open fi
1 min read
Comparison of Exception Handling in C++ and Java
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.We can catch Exception objects to catch all kinds o
4 min read
Exception Handling and Object Destruction in C++
An exception is termed as an unwanted error that arises during the runtime of the program. The practice of separating the anomaly-causing program/code from the rest of the program/code is known as Exception Handling. An object is termed as an instance of the class which has the same name as that of the class. A destructor is a member function of a
4 min read
Socket Programming in C/C++: Handling multiple clients on server without multi threading
This tutorial assumes you have a basic knowledge of socket programming, i.e you are familiar with basic server and client model. In the basic model, server handles only one client at a time, which is a big assumption if you want to develop any scalable server model. The simple way to handle multiple clients would be to spawn new thread for every ne
6 min read
Practice Tags :
three90RightbarBannerImg