How to Open and Close a File in C++?
Last Updated :
08 Feb, 2024
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++.
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++
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ofstream fio( "abc.txt" , ios::app);
if (fio.is_open()) {
cout << "File opened successfully." << endl;
fio << "This text is appended to the file." << endl;
fio.close();
cout << "File closed." << endl;
}
else {
cout << "Error opening file!" << endl;
}
return 0;
}
|
Output
File opened successfully.
File closed.
Share your thoughts in the comments
Please Login to comment...