I have a program that will create a simple txt file in the same directory as the compiled .exe:

ofstream output("myfile.txt", ios::binary | ios::trunc);

At the end of my program, I have this to remove it:

remove("myfile.txt");

Both of these work well, however, I want the file deleted if the user closes the cmd window unexpectedly, accidently, or they end the process.

有帮助吗?

解决方案

The standard way to clean up your process is to register a function with 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 );
}

This will run if the process is exited gracefully, platform details notwithstanding.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top