문제

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