Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Streams in C++
3.
File Stream Operations Classes
4.
File Handling C++
4.1.
Opening a File
4.2.
Reading from a File
4.3.
Writing to a File
4.4.
Closing a File
5.
Example for File Operations
6.
Frequently Asked Questions
6.1.
What are >> and << operators in C++?
6.2.
What is modularity in C++?
6.3.
What is containership in C++?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

C++ Files and Streams

Introduction

A program communicates with the target environment by reading and writing files. Files are used to permanently store data in a storage device. File handling is a mechanism for storing a program's output in a file and performing different operations on it. A stream is an abstraction that depicts a device that performs input and output actions. 

C++ Files and Streams

Files are important in programming because they store data. File handling in C++ is a method of saving the output of a program in a file and executing various operations on it. This tutorial will show you the various concepts behind C++ files and streams.

You can also read about, cpp abstract class

Streams in C++

We provide input to the executing program, and the execution program returns the output. Stream refers to the series of bytes sent as input to the executing program and the sequence of bytes returned as output from the executing program. In other words, streams are nothing more than the sequential flow of data. 

"Console I/O operation" refers to the input and output operations between the running program and devices such as the keyboard and monitor. The "disk I/O operation" refers to the input and output operations between the executing application and files.

File Stream Operations Classes

S.No.

Class Name

Description

1 ios The abbreviation ios stands for input-output stream. This class serves as the foundation for all other classes in this class hierarchy. It contains the capabilities required for input and output operations by all other derived classes.
2 istream istream is an abbreviation for input stream. This class derives from the 'ios' class. It is in charge of the input stream. Input functions such as get()getline(), and read() are declared in this class.
3 ostream ostream is an abbreviation for the output stream. This class derives from the 'ios' class. This class is in charge of the output stream. This class contains output operations like put() and write().
4 fstreambase This class provides operations that are shared by all file streams. It is the foundation for the fstream, ifstream, and ofstream classes.  This class has the open() and close() functions.
5 ifstream This class implements input operations. It includes an open() function with the default input mode. The istream's get(), getline(), read(), seekg(), and tellg() functions are inherited.
6 ofstream This class is responsible for output operations. It includes an open() method with the default output mode. The ostream's put(), write(), seekp(), and tellp() functions are inherited.
7 fstream This class represents the file stream in general, and it possesses the characteristics of both ofstream and ifstream, which means it can create files, write data to files, and read data from files.
8 filebuf Its function is to configure the file buffers to read and write. We can also utilize the file buffer member function to calculate the file's length.

File Handling C++

 File Handling in C++ is a technique for storing a program's output in a file and performing different operations on it. It is an important part of C++ files and streams. Files help in the permanent storing of data on a storage device. "Data" is widely used to refer to known facts or information. Data is extremely important in today's world. It aids in describing, diagnosing, forecasting, and prescribing. But, in order to accomplish all of this, we must first store it somewhere. 

To deal with data storage, almost every programming language offers a 'File Handling' mechanism. In C++, we have a number of file-handling techniques. Examples are ifstream, ofstream, and fstream. These classes are subclasses of the fstreambase and iostream classes. Because these classes for managing disc files are declared in fstream, we must include the fstream library in our program. File handling entails a variety of activities, such as opening, reading, writing, and closing a file. We will go over each operation in detail.

Opening a File

The open() method is used to open a file in order to read or write data to it. We read the file with the 'ifstream' library and write it with the 'ofstream' or 'fstream' library. 

Syntax:

open( ‘File Name’, Mode)
You can also try this code with Online C++ Compiler
Run Code

 

The first parameter of the open() member function indicates the name and location of the file to be opened, and the second argument determines the mode in which the file should be opened.

There are several ways to open the file. Let's have a look at each of them in the table below:

S.No.

Mode 

Description

1 ios::app Everything written to that file will be appended to the end.
2 ios::ate Opens an output file and moves the read/write control to the end of it.
3 ios::in Opens a file to read.
4 ios::out Opens a file to write.
5 ios::trunc If the file already exists, it will be shortened before being opened.

Reading from a File

The stream extraction operator (>>) is used to read data from a file into your application, exactly as it is used to input data from the keyboard. The only change is that instead of the cin object, you use an ifstream or fstream object.

Writing to a File

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

Closing a File

To accomplish close operation, we use close(). When a C++ application terminates, it flushes all streams, releases all allocated memory, and closes all open files. However, it is always a good habit for a programmer to close all open files before terminating the program. 

Syntax: 

File_Name.close();
You can also try this code with Online C++ Compiler
Run Code

Example for File Operations

The C++ program that implements all the file operations is shown below. After writing information entered by the user to a file called temp.txt, the application reads the file and displays it on the screen.

Code:

#include <fstream>
#include <iostream>
using namespace std;
// C++ Files and Streams Example
int main () {
   char data[100];
   // open a file in write mode.
   ofstream output_file;
   output_file.open("temp.txt");
   cout << "Writing text to the file" << endl;
   cout << "Enter your name: "; 
   cin.getline(data, 100);

   // write inputted data into the file.
   output_file << data << endl;

   cout << "Enter your age: "; 
   cin >> data;
   cin.ignore();
   
   // Again, write inputted data into the file.
   output_file << data << endl;

   // close the opened file.
   output_file.close();

   // open a file in read mode.
   ifstream input_file; 
   input_file.open("temp.txt"); 
 
   cout << "Reading from the file" << endl; 
   input_file >> data; 

   // write the data at the screen.
   cout << data << endl;
   
   // Again, read the data from the file and display it.
   input_file >> data; 
   cout << data << endl; 

   // close the opened file.
   input_file.close();
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

Writing text to the file
Enter your name: John Snow
Enter your age: 21
Reading from the file
John Snow
21

 

The above code gives the implementation of C++ files and streams. It makes use of additional cin object functions, such as the getline() function to read the line from outside and the ignore() function to ignore the excess characters left by the previous read command.

Also see, Abstract Data Types in C++

Frequently Asked Questions

What are >> and << operators in C++?

In general, >> and act as shift operators, whereas when used with cin, it acts as an extraction operator. Similarly, when we use cout, it operates as an insertion operator.

What is modularity in C++?

Modularity, which is closely related to Encapsulation, is a method of mapping enclosed abstractions into actual and physical modules. It is a notion that divides individual programs into discrete modules.

What is containership in C++?

Containership is a relationship in C++ in which the object of one class is nested within the object of another class. The class that contains the object is known as a container class, while the class that stores the item is known as a contained class.

Conclusion

C++ files and streams provide a powerful and versatile approach to managing input and output operations. They enable seamless data reading and writing to and from files, making it easier to modify and process data. In this tutorial, we discussed what C++ Files and Streams are, as well as several kinds of file stream operations and file handling methods.

To better understand the topic, you can refer to File Handling in Cpp and Input/Output Streams.

For more information, refer to our Guided Path on CodeStudio to upskill yourself in PythonData Structures and AlgorithmsCompetitive ProgrammingSystem Design, and many more! 

Head over to our practice platform, CodeStudio, to practice top problems, attempt mock tests, read interview experiences and interview bundles, follow guided paths for placement preparations, and much more!

Live masterclass