Open and Close a File in C++
The fstream class contains the std::fstream::open() function that can be used to open files in different modes.
Syntax of fstream::open()
fstream_object.open(filename, mode);
The modes can be of three types:
- std::ios::in: This mode is used to open a file for reading only.
- std::ios::out: This mode is used to open a file for writing. If there is already content in the file then it will be overwritten in this mode.
- std::ios::app: This mode is called the append mode in which we open a file for writing at the end of the file.
We can close the file using std::fstream::close() function.
Algorithm
1. We will first create an fstream object.
2. Then we open the file using open() function in write mode(ios::out)
2. We then write some data to the file.
3. At the end, we close the file using close() function
C++ Program to Open and Close a File
C++
// C++ program to demonstrate how to open and close a file #include <fstream> #include <iostream> using namespace std; int main() { // create and ofstream object and open the file in // append mode ofstream fio( "abc.txt" , ios::app); // Check if the file is opened successfully if (fio.is_open()) { cout << "File opened successfully." << endl; // Append content to the file fio << "This text is appended to the file." << endl; // Close the file fio.close(); cout << "File closed." << endl; } else { // Display error if file was not opened cout << "Error opening file!" << endl; } return 0; } |
File opened successfully. File closed.
How to Open and Close a File in C++?
In C++, we can open a file to perform read and write operations and close it when we are done. This is done with the help of fstream objects that create a stream to the file for input and output. In this article, we will learn how to open and close a file in C++.