C++ File Handling

It is sometimes necessary to save the user's information in a file for later use. You can later retrieve the information after saving it in a file. A file aids in the permanent storage of information.

A file is a collection of bytes stored on a storage device such as tape, magnetic disc, or hard disc. File input and output operations in C++ are handled by the C++ standard library's component header file "fstream".

A file is a type of object in C++.

The "fstream" library includes a set of operations for dealing with file-related input and output. It defines several classes that aid in file input and output operations.

To store, retrieve, or delete data from or into a file, you must first understand how to handle it. As a result, in this section, I'll try to explain as much as possible to help you become a better C++ file handler.

The following is a list of topics that will be covered in the section "File Handling in C++."

From the nine sub-topics of "file handling in C++," the first two will be covered in this post: "File streams in C++" and "Data files in C++." The remaining topics will be covered in a separate post beginning with the next post.

File streams in C++

At the most basic level, a stream is the name given to a data flow. At its most basic, data is just binary data with no concept of data type. Various streams are used to represent various types of data flow, such as whether data is flowing into or out of memory.

Each stream is associated with a specific class containing the member functions and definitions for managing that specific type of data flow. The "ifstream" class, for instance, represents the input disc files.

Input stream refers to the stream that provides data to the program. It reads the file and transfers the data to the program. Output stream refers to the stream which receives data from the program. It stores the received data in the specified file.

The C++ file I/O system includes a collection of classes that are responsible for defining the file handling methods. These classes are declared in the header file known as "fstream". Its purpose is to manage the files that are stored on the disc. Because of this, we need to incorporate this file into a program that is capable of working with files.

The list below briefly describes all three "header files" that are most commonly and widely used in C++ file handling programs.

Here's a simple example program using C++ file streams. This program only requires you to enter the file name and a line to store the line in this file.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
   string inform, fname;

   cout << "Enter file name: ";
   getline(cin, fname);

   ofstream fout(fname);
   if (!fout)
   {
      cout << "Error creating the file!\n";
      return 0;
   }

   cout << "Enter a line to store in the file: ";
   getline(cin, inform);
   fout << inform << "\n";

   cout << "\nThe information you entered was successfully saved!\n";
   fout.close();

   return 0;
}

The following snapshot shows the initial output produced by the above program:

C++ file handling example

Now enter the input, that is, type the name of the file to be created, for example, "myfile.txt," and press the ENTER key to save it in the current directory. Then type "Hello there" and press the ENTER key again to save this text in the newly created file. The snapshot below depicts the sample run with these inputs:

C++ file handling program

The "current directory" refers to the location of the above C++ source code. Because I saved the preceding C++ source code in the directory "C:\Users\DEV\Documents\fresherearth," a new file named "myfile.txt" will be created. The following snapshot was taken from the current directory and includes the newly opened file:

c++ file handling code

Now, let me explain the above code to you so you understand how the program works. I'll only go over the file handling code fragments. Other code fragments used in the preceding program have been discussed in previous posts.

Data files in C++

Files are required to permanently store any information for future use. The same is true for data files.

Data files are files that store information about a specific application for later use. The data files can be saved in one of two ways:

  1. Text files
  2. Binary files

Text file

Information is stored in a text file using ASCII characters. To denote the end of a line of text in a text file, the End of Line (EOF) character is used.

Binary file

There is no line delimiter present in a binary file's data structure. In addition, translations do not take place within a binary file. As a consequence of this, a program can read and write binary files significantly more quickly and easily compared to text files. The best way to store program information is in a binary file, provided that the file does not need to be read by people or ported to a different type of system.

C++ File Handling Program

Before we conclude this post's discussion, let me provide an example of file handling in C++. As a result, I wrote the following program, which will receive the file name from the user at program runtime, then receive the content to store in the file, and finally allow the user to view the file's content on the output console.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
   ifstream ifile;
   string inform, fname;
   char ch;
   cout << "Enter file name: ";
   getline(cin, fname);
   ifile.open(fname);
   if (ifile)
   {
      cout << "The entered file already exists. Please try again.\n";
      return 0;
   }
   else
   {
      ifile.close();
      ofstream fout(fname);
      if (!fout)
      {
         cout << "Error creating the file!\n";
         return 0;
      }
      cout << "Enter a line to store in the file: ";
      getline(cin, inform);
      fout << inform << "\n";
      cout << "\nThe information you entered was successfully saved!\n";
      fout.close();
      cout << "\nDo you want to read the file \"" << fname << "\"? (y/n): ";
      cin >> ch;
      if (ch == 'y' || ch == 'Y')
      {
         string myline;
         ifstream ifile(fname);
         while (getline(ifile, myline))
         {
            cout << myline;
         }
         ifile.close();
      }
   }
   cout << endl;
   return 0;
}

The following box shows the sample run of the above program with user inputs: "fresherearth.txt" as the name of the file, "Learning file handling in C++ programming is enjoyable." as the line of text to store in the newly created file, and "y" as the choice to read the newly created file back on the output console.

Enter file name: fresherearth.txt
Enter a line to store in the file: Learning file handling in C++ programming is enjoyable.

The information you entered was successfully saved!

Do you want to read the file "fresherearth.txt"? (y/n): y
Learning file handling in C++ programming is enjoyable.

Process returned 0 (0x0)   execution time : 9.583 s

More Examples

C++ Quiz


« Previous Tutorial Next Tutorial »