We know that calling the open() method to open a file is the process of establishing a connection between the file stream object and the file. Therefore, calling the close() method to close an opened file can be understood as severing the connection between the file stream object and the file. Note that the close() method’s function is merely to sever the connection between the file stream and the file; the file stream will not be destroyed and can still be used to associate with other files later.The usage of the close() method is very simple, and its syntax format is as follows:void close( )As you can see, this method requires no parameters and has no return value.For example:
#include <fstream>
using namespace std;
int main()
{
const char *url="https://six.club/articles";
ofstream outFile("url.txt", ios::out);
// Write string to url.txt file
outFile.write(url, 30);
// Close the opened file
outFile.close();
return 0;
}
When you run the program, a file named url.txt will be generated in the same directory as the program, and the data stored inside is:https://six.club/articlesSome readers may notice that even if the close() method is not called in the above program, it can still successfully write the url string to the url.txt file. This is because when the file stream object’s lifecycle ends, its destructor is automatically called, which first calls the close() method to sever its association with any file before finally destroying it.
It is strongly recommended that readers manually call the close() method to close files opened with the open() method, as this can help avoid some bizarre errors in the program!
When the file stream object is not associated with any file, calling the close() method will fail, setting the failbit state flag for the file stream, which can be captured by the fail() member method.For example:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const char *url="https://six.club/articles";
ofstream outFile;
outFile.close();
if (outFile.fail()) {
cout << "An error occurred during the file operation!";
}
return 0;
}
The program execution result is:An error occurred during the file operation!The editor has compiled a set ofC languagelearning materials. If you need them, you can send a private message to@C Language Learning Allianceand replyto receive materials. Everyone is welcome to follow; I will share relevant technical articles in a timely manner when I have time. Your attention and likes are very important to me, thank you all for clicking to follow~*Disclaimer:This article is compiled from the internet, and the copyright belongs to the original author. If there is any incorrect source information or infringement of rights, please contact us for deletion or authorization matters.