Till now, we have seen the use of iostream standard library that provides us with cin
and cout
methods to take input and print output respectively. Here we will learn about another library to handle files.
Files are used to store the data permanently in the storage device and a standard C++ library called fstream allows us to work with files.
fstream Library
The fstream Library provides us with three classes that help us to read and write from the files in C++. And these classes are:
- fstream: This class generally represents a file stream. It is used to create files, write or read data from or to the files.
- ifstream: This class represents an input stream and used to read the data from the files.
- ofstream: This class represents an output stream and used to write the data to the files.
Open a file
We can not perform any operation on file without opening it first. If you want to perform a write operation on the file then open the file using fstream or ofstream objects. If you want to perform a read operation on the file then open the file using ifstream object.
There is a function called open()
which is a member of all three classes (fstream, ifstream, and ofstream) and is used to open a file. The syntax to open a file is:
open (file_name, mode);
file_name
: This simply indicates the name of the file to be opened.mode
: It defines the mode in which the file should be opened. It is opetaional. There are several modes given below.
Mode | Description |
ios:: app | Append mode. The output sent to the file is appended to it. |
ios::ate | At end mode. It opens the file for the output then moves the read and write control to the end of the file. |
ios::in | Input mode. It opens the file for reading. |
ios::out | Output mode. It opens the file for writing. |
ios::trunc | Truncate mode. If a file exists then before opening the file its contents are discarded. |
Also while opening a file we can combine the above modes together using OR operator (|
) such as:
1 2 | ofstream file; file.open("file_name", ios::out | ios::trunc); |
Default Modes:
As stated above the mode in an open() function is optional and if we do not provide the mode then the following default mode will be assigned to the respective classes.
Class | Mode |
---|---|
ifstream | ios::in |
ofstream | ios::out |
fstream | ios::in | ios::out |
Close a file
Once the program is terminated in C++, it automatically closes the opened files. However, it is recommended to practice closing a file every time you open a file.
Just like a function open() is there to open a file, the fstream, ofstream, and ifstream objects also have a close() function. The syntax is pretty simple.
void close();
Example: C++ program to open and close a file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <iostream> #include <fstream> using namespace std; int main() { fstream file; file.open("file.txt", ios::out); //check if file creation is failed or not if (!file) { cout << "File is not created!"; } else { cout << "File is created successfully."; file.close(); } return 0; } |
//OutputFile is created successfully.
After successful execution of the above code, you may check the directory where your c++ program file is present, there you will find a new text file with file.txt name.
Writing to a file
Below is the example of C++ to write to a file. We will write to a text file called file.txt using the stream insertion operator (<<). Here we use ofstream or fstream object instead of the cout object.
Example: C++ to write in a file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | #include <iostream> #include <fstream> using namespace std; int main() { ofstream file("file.txt"); //check if file is opened or not if (file.is_open()) { file << "This is Simple2Code.com.\n"; file << "Learn Programming Language.\n"; file.close(); } else { cout << "File failed to open"; } return 0; } |
After successful execution of the program, you can open your file.txt and you will see the following sentence inside that file.
This is Simple2Code.com.
Learn Programming Language.
Reading from a file
Below is the example of C++ to read from a file. We will from a text file called file.txt using the stream extraction operator (>>). Here we use ifstream or fstream object instead of the cin object.
Example: C++ to read from a file.
Now before running the program, you must create a file and write some text in it as for this example, we created a file called file.txt and wrote the following text in it.
This is Simple2Code.com.
Learn Programming Language.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <iostream> #include <fstream> using namespace std; int main() { string str; ifstream file("file.txt"); //check if file is opened or not if (file.is_open()) { while (getline(file, str)) { cout << str << endl; } file.close(); } else { cout << "File failed to open"; } return 0; } |
After successful execution of the program, you will see the following output (String from opened file.)
This is Simple2Code.com.
Learn Programming Language.
Example: Read and Write in C++
Here, we will see an example where we will write some data in a text file called file.txt and then read those from the file using C++ FileStream. To write the data, we will take user input.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include <iostream> #include <fstream> using namespace std; int main() { char data[100]; //WRITE mode ofstream writeFile; writeFile.open("file.txt"); cout << "Writing to a file:" << endl; cout << "Enter your name: "; cin.getline(data, 100); writeFile << data << endl; //writing the entered data cout << "Enter your age: "; cin >> data; cin.ignore(); writeFile << data << endl; //writing the entered data writeFile.close(); //file closed //READ mode string str; ifstream readFile; readFile.open("file.txt"); cout << "\nReading from a file:" << endl; while (getline(readFile, str)) { cout << str << endl; } readFile.close(); //file closed return 0; } |
After Execution, a file name file.txt will be created and the following entered will be present in that file.
Writing to a file:
Enter your name: John Markson
Enter your age: 29
Reading from a file:
John Markson
29