Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 让gcc在终止时像C流一样刷新所有打开的FStream_C++_Gcc - Fatal编程技术网

C++ 让gcc在终止时像C流一样刷新所有打开的FStream

C++ 让gcc在终止时像C流一样刷新所有打开的FStream,c++,gcc,C++,Gcc,考虑以下代码: #include <cstdio> #include <iostream> #include <fstream> using namespace std; int main() { ofstream *file1 = new ofstream("file1.txt"); (*file1) << "hi\n"; FILE *file2 = fopen("file2.txt", "w"); fprint

考虑以下代码:

#include <cstdio>
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ofstream *file1 = new ofstream("file1.txt");
    (*file1) << "hi\n";
    FILE *file2 = fopen("file2.txt", "w");
    fprintf(file2, "hi\n");
    abort();
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
ofstream*file1=新的ofstream(“file1.txt”);

(*file1)毫无疑问,没有合法途径

但在GCC4.1中,您可以使用
\uuuu属性((析构函数))
进行破解。这将需要使流成为全局流,并使用
退出(-1)
而不是
中止

整个故事看起来像:

ofstream *file1;

int __attribute__ ((constructor))
pre_exec_fn (void)
{
  file1 = new ofstream("file1.txt");
}

int __attribute__ ((destructor))
post_exec_fn (void)
{
  file1->flush();
  delete file1;
}

int main()
{
    (*file1) << "hi\n";
    exit(-1);
}
流*文件1的
;
int _属性_((构造函数))
预执行董事(无效)
{
file1=流的新文件(“file1.txt”);
}
int _属性_((析构函数))
后执行官(无效)
{
file1->flush();
删除文件1;
}
int main()
{

(*file1)我持Linux或Posix的观点。如果你只想严格遵守语言标准(即),你需要使用构造函数和析构函数

例如,您可以使用一些智能指针,即使用和声明:

 std::unique_ptr<std::ofstream> file1= new ofstream("file1.txt");
std::unique_ptr file1=newofstream(“file1.txt”);
我强烈建议使用的更新版本,即
g++
version 4.9.1。您的4.1版本非常旧,不符合C++11标准

从Linux的角度来看,如果程序以信号终止,情况就不同了(请参阅;注意,很少有函数可以合法地从信号处理程序调用,
exit
不能,有些信号无法捕获,如果没有安装显式的信号处理程序,一些信号会立即终止进程),通过或从
main
返回(其中出现隐式
退出)

如果不使用任何智能指针,您还可以注册一个退出处理程序函数,该函数将显式刷新或关闭程序显式保留在某处的所有流(您需要管理如何和在何处)。请注意,不使用
退出
(或syscall)


正如回答的那样,您也可以使用特定于GCC的(例如,
\uuu属性(构造函数))

作为C99文件部分的一部分,程序终止的其他路径(如调用中止函数)不需要正确关闭所有文件。您的示例可以更好地使用流文件1的
退出()
exit
不会销毁具有自动存储持续时间的对象,这意味着
file1
,但它会刷新并关闭C流。实际上,
printf()
会在“\n”上刷新,所以您得到该文本不是因为
文件
流在中止时刷新()@Slava,只有在流是行缓冲的情况下才可以。@NeilKirk,据我所知,使用信号处理程序调用析构函数不是一个好方法。gcc 4.1.2不是已经有7年的历史了吗?详尽的回答!谢谢(向上投票)。我在这里没有考虑智能指针的用法。即使在gcc 4.1中,也可能会为iostream创建一个简单的包装器。但是所有这些(包括我的答案)只有在使用
exit
时才起作用。glibc是否会在
abort
上调用
unique_ptr
析构函数?我的实验表明,它不会起作用。