Search code examples
c++file-ioexittemporary

Delete .txt file when program closes/exits (X Button)


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.


Solution

  • 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.