There are two ways to close a C++ file: using the fclose() function (applicable to C stream files) and using the close() member function of the ifstream and ofstream classes (applicable to C++ standard library file streams). These methods ensure that the file is closed before the program ends to avoid resource leaks, and the close() member function can automatically close the file, while fclose() requires an explicit call.
How to close a file using C++
File manipulation is a common task in programming. In C++, there are several ways to close a file. This article will detail the method of closing C++ files and provide a practical case to demonstrate how to use it.
Method 1: Use the fclose() function
fclose()
is a standard C function used to close a file. It accepts a FILE* type pointer as parameter, pointing to the file to be closed. The syntax is as follows:
int fclose(FILE *stream);
Method 2: Use the close() member function of the ifstream and ofstream classes
ifstream
and # in the C++ standard library The ##ofstream class provides the
close() member function for closing the file. The syntax is as follows:
void close();
Practical case
The following code example demonstrates how to use thefclose() function to close a file:
#include <stdio.h> int main() { // 打开一个文件 FILE *file = fopen("test.txt", "w"); // ... 在文件中写入数据 ... // 关闭文件 int result = fclose(file); // 检查是否关闭成功 if (result != 0) { printf("无法关闭文件!\n"); return 1; } printf("文件已成功关闭。\n"); return 0; }
close() member function of the
ifstream class to close a file:
#include <iostream> #include <fstream> int main() { // 打开一个文件 std::ifstream file("test.txt"); // ... 从文件中读取数据 ... // 关闭文件 file.close(); // 检查是否关闭成功 if (!file.is_open()) { std::cout << "文件已成功关闭。" << std::endl; } else { std::cout << "无法关闭文件!" << std::endl; } return 0; }
Note:
function to explicitly close.
and
ofstream objects, automatic closing can be done using the destructor, but explicit closing ensures that the file is closed as quickly as possible.
The above is the detailed content of How to close a file using C++?. For more information, please follow other related articles on the PHP Chinese website!