我想在退出程序时运行一个带参数且返回值为void的函数。我使用以下代码来实现它:
#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;
}
程序退出时,会在我指定的路径下创建一个文件,写入指定的内容。当我使用g++生成可执行程序时,程序能够在退出时创建文件。但是当我使用MSVC生成可执行程序时,程序退出时无法创建文件。我认为 std::atexit 函数在 MSVC 编译器中不起作用。 我的g++版本是11.2.0,MSVC版本是19.37.32825
有没有办法让我的代码在MSVC编译器中工作,即程序退出时得到与g++编译器相同的结果
问题是你的程序有一个无限循环(while(1){ /.../ })。
#include<iostream>
#include<fstream>
#include<windows.h>
#include<functional>
void Exit(std::string s) {
std::ofstream ofs;
ofs.open("E:\\code\\file.txt", std::ios::out);
ofs << s << std::endl;
ofs.close();
}
int main() {
auto callback = std::bind(Exit, "test");
static std::function<void()> atExitCallback = callback;
atexit([] { atExitCallback(); });
system("pause");
return 0;
}