I want to run a function with parameters and a return value of void when exiting the program. I use the following code to implement it:
#include<bits/stdc++.h>
#include<windows.h>
using namespace std;
void Exit(string s){
ofstream ofs;
ofs.open("E:\code\file.txt",ios::out);
ofs << s << endl;
ofs.close();
}
int main(){
auto callback = std::bind(Exit, "test");
static std::function<void()> atExitCallback = callback;
atexit([] { atExitCallback(); });
while(1){
cout << "running..." << endl;
Sleep(500);
}
system("pause");
return 0;
}
When the program exits, it will create a file in the path I specified and write the specified content. When I use g++ to generate executable programs, the program is able to create files when exiting. But when I use MSVC to generate executable programs, the program is not able to create files when exiting. I think the std::atexit function is not working in the MSVC compiler.
My g++ version is 11.2.0,MSVC version is 19.37.32825
Is there a way to make my code work in the MSVC compiler, that is, to get the same result as the g++ compiler when the program exits
Ember1597 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2