In this tutorial, you’ll learn how to read and write files in C++. This is a basic and easy-to-understand lesson in which we will cover the syntax and usage of file handling in C++ in great detail. We will also touch upon some examples which will help us understand the concepts in a practical setting.
Throughout this tutorial, we will use fstream
which is the standard C++ library for reading and writing to files.
File Handling Data Types
The standard fstream
library exposes three data types to deal with file handling; ifstream
, ofstream
and fstream
. The ifstream
data type facilitates in file handling by allowing to read information from a file. The ofstream
data type facilitates file handling by allowing to create and write information on a file. Lastly, fstream
is a general data type that has the overall capabilities of handling a file i.e. creating a file, reading from a file, and writing to a file.
Note that in order to use these data types, we must include both iostream
and fstream
as headers in the source file.
#include <iostream>
#include <fstream>
File Handling Steps
Generally, there are three steps involved in order to perform an end to end execution of reading and/or writing to a file. In this section, we will discuss these steps in great detail including the syntax and support examples.
Opening a File
In order to perform read/write operations, we must open the file first. This allows the program to know exactly which file we need to currently work on. If we want to open the file for reading, we can use the ifstream
data type. For writing to a file, we can use the ofstream
data type. The safest option is to open the file using fstream
data type because we can use the same variable pointer for both reading and writing purposes.
The fstream
header provides a function called open
which opens the file for further usage. Following is the basic syntax to open a file in C++.
void open(const char* yourFilename, ios::openmode fileMode)
The above function takes two arguments. The first argument is the filename which we wish to use for reading/writing. The second argument is the mode that tells the program to open the file for a specific set of operational modes.
Let’s look at an example usage to properly understand it.
ifstream myFile;
myFile.open("test.txt", ios::in);
You might be wondering what exactly ios::in
is! Well, it is the same operational mode which we discussed above. By using ios::in
, we have let the program know that the file test.txt
will be used only for input operations. In other words, we can only read from test.txt
using the myFile
variable.
We can open the same file using fstream
as well.
fstream myFile;
myFile.open("test.txt", ios::in | ios::out);
This time we have two operational modes separated by a |
symbol. Other than the ios::in
, we have also included the ios::out
mode. It means that we can both read and write this time using the myFile
variable.
There are a variety of different operational modes. You may read further about them here.
File Reading and Writing
After opening the file, we are now allowed to perform read and/or write operations on that file depending upon whichever use case we want. In this subsection, we will take a look at both reading from a file and writing to a file. Let’s start by writing some dummy text to a file. Once we are done with writing, we will use the same file to read its contents and print them on the console.
Writing to a File
Look at the following code snippet which writes a piece of dummy text in the file dummy.txt
.
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char text[150] = "Welcome to CodeZen tutorials!\nI am Emad Bin Abid; a Full Stack Developer and a Technical Blogger.\n";
// opening the file for writing
fstream writeFile;
writeFile.open("dummy.txt", ios::out);
// writing to the file
writeFile << text << endl;
// freeing up memory by closing the file
writeFile.close();
}
Pretty much self-explanatory, no? If you’re worried about that writeFile.close()
statement then hold on for a bit until we discuss about closing a file in the next subsection.
Now let’s use the same file dummy.txt
for reading and retrieve the text which we just wrote in the file.
Reading from a File
The following code snippet reads the file dummy.txt
line by line and prints the result on the console window.
#include <fstream>
#include <iostream>
using namespace std;
int main () {
string text;
// opening the file for reading
fstream readFile;
readFile.open("dummy.txt", ios::in);
// reading from the file
while (getline(readFile, text))
{
cout << text << endl;
}
// freeing up memory by closing the file
readFile.close();
}
The above code piece will generate the following output in the console window.
Welcome to CodeZen tutorials!
I am Emad Bin Abid; a Full Stack Developer and a Technical Blogger.
Closing a File
Although, when the program finishes its execution, it frees out the memory. But generally, it is recommended to manually free out the memory to avoid memory leakages and extra overhead on the program. We can release the memory occupied for file handling by closing the file using the close
function provided by fstream
header.
myFile.close();
Wrapping Up
That’s all about file handling in C++. I hope it was an easy tutorial to help you familiarise yourself with the basics of reading/writing operations of files in C++. We cannot assess our learning unless we practically implement what we learn so I highly recommend doing practical hands-on exercises related to file handling. Try out cool things on your own and share with us what interesting stuff have you come up with.
Feel free to ask your questions in the comments section below. If you wish to learn more about React, you can check out our collection of C++ tutorials.
Comments