CLOSE()
The close() function is used to explicitly close a file that has been opened for reading or writing. When close() is called, any data remaining in the stream’s buffer is automatically flushed to the file, ensuring that all pending output is saved. After a file is closed, the associated file handle is released, allowing the operating system to reuse it. While C++ automatically closes files when their stream objects go out of scope (via the destructor), explicitly calling close() is considered good practice, especially in long-running programs or when opening multiple files, because it provides more precise control over resource management and guarantees that data is written to disk immediately.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string filename = "data.txt";
ofstream myFile;
// Attempt to open the file "data.txt"
myFile.open(filename);
// Check if the file was opened successfully
if(myFile.is_open()) {
cout << "File opened successfully!" << endl;
// Write content to the file
myFile << "Hello, world!" << endl;
// Close the file
myFile.close();
// Check if the file is closed now
if(!myFile.is_open()) {
cout << "File closed successfully!" << endl;
}
} else {
cout << "File opening failed!" << endl;
}
cout << "Program complete." << endl;
return 0;
}
Last updated