![]() |
VOOZH | about |
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++.
The fstream class contains the std::fstream::open() function that can be used to open files in different modes.
fstream_object.open(filename, mode);
The modes can be of three types:
We can close the file using std::fstream::close() function.
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
File opened successfully. File closed.