我有一个程序,它将在与编译的 .exe 相同的目录中创建一个简单的 txt 文件:
ofstream output("myfile.txt", ios::binary | ios::trunc);
在我的程序结束时,我可以将其删除:
remove("myfile.txt");
这两种方法都工作得很好,但是,如果用户意外地、意外地关闭了 cmd 窗口,或者结束了进程,我希望删除该文件。
最佳答案
清理进程的标准方法是使用 atexit
注册一个函数。
void clean_myfile {
std::remove( "myfile.txt" );
}
int main() {
std::ofstream output("myfile.txt", std::ios::binary | std::ios::trunc);
std::atexit( clean_myfile );
}
如果进程正常退出,无论平台详细信息如何,这都会运行。
关于c++ - 程序关闭/退出时删除 .txt 文件(X 按钮),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16869190/