File handling in c++

F

Today, we are going to see file handling in c++ where we will be covering reading and writing files. We would highly recommend going through the basics of C++ before moving on. File handling has tons of use cases and it is an essential topic for any programmer. So without any delay, let us start a deep dive into it

Filing

In C++, file handling is a mechanism for storing and processing data in files. Files aid in the permanent storing of data on a storage device. Data is known facts or information  

Benefits of File Handling in C++

The following are some of the reasons behind the popularity of file management:

Reusability: It aids in the preservation of data or information that a program generates after it is run.

Large storage capacity: When you use files, you won’t have to worry about saving data in bulk.

Time savvy solutions: Certain programs necessitate a large amount of user input.

Portability: You may easily move the contents of a file from one computer system to another without fear of losing information.

ofstream: A stream class that allows you to write to files.

ifstream: A file-reading stream class.

fstream: A stream class that allows you to read and write data from and to files.

These classes are from instream and ofstream, either directly or indirectly. We’ve already used objects of these types: cin is an object of the ifstream class, and cout is an object of the ofstream class. As a result, we’ve already been employing classes associated with our file streams. We utilize our file streams in the same way that we use cin and cout, with the exception that these streams must link with physical files.

Writing file using Ofstream

// Let's include basic libraries for performing IO
#include <iostream>
#include <fstream>
using namespace std;

int main() {
	ofstream demoFile; // creating of srream object
	//opening file, if file already exists it will open it, else it will create new file
	demoFile.open("demo.txt");

	// now we will iterate 10 times and put value of index on file
	for (int i = 0; i < 10; i++) {
		demoFile << i + 1 << endl;
	}

	//closing the stream
	demoFile.close();
	return 0;
}

The most common operation performed on an object belonging to one of these types is to link it to an actual file. This operation is “opening a file.” A stream (i.e., an object of one of these classes; In the previous example, this was demoFile) represents an open file within a program, and any input or output operation done on this stream object will apply to the actual file associated with it.

We utilize the member function open: to open a file with a stream object. Where filename is a string that represents the name of the file to open, and mode is an optional parameter that contains a combination of flags. Some of these flags are.

We can combine these flags using | operator, in previous example, we can open the file in the following way.

demoFile.open("demo.txt", ios::out | ios::app);

When we’ve completed our input and output actions on a file, we’ll close it to notify the operating system and make its resources available again. The stream’s member function close is for this purpose. This member function shuts the file and flushes the associated buffers:

myfile.close();

After using this member function, the stream object can be used to open another file, and the file can be opened by other processes again. If an object is destroyed while it is still associated with an open file, the destructor executes the close member function automatically.

Using Ifstream

// including necessary files for performing FILE IO
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    string fileName = "demo.txt";
    string line; // represent line read by geline function
    ifstream myfile(fileName);
    if (myfile.is_open()) // we will check if file is opened successfully then we will proceed
    {
        // now reading line by line untill data ends
        while (getline(myfile, line))
        {
            cout << line << '\n';
        }
        myfile.close();
    }

    else cout << "Unable to open file " << fileName;

    return 0;
}

The final example reads a text file and displays the contents on the screen. Using getline, we developed a while loop that reads the file line by line. The result given by getline is a reference to the stream object itself, which, when evaluated as a boolean expression (as in this while-loop), returns true if the stream is ready for future operations and false if the file has reached its end or if an error has occurred.

Conclusion

In this article, we saw basic of file handling in c++ with proper concepts and examples. To see similar articles, go through our website from here. To get deeper concepts of files in c++, we recommend going through this.

Add comment

Tutor Network