2017-07-03 84 views
0

有没有人知道如何将stderr重定向到一个没有缓冲的文件?如果可能的话,你可以向我展示一个简单的Linux代码(Centos 6)的C++语言代码..?!如何将stderr重定向到没有任何缓冲区的文件?

+0

'stderr'默认情况下不进行缓冲。 – Barmar

+0

SO不是免费的编码服务。你必须尝试自己解决问题。如果无法正常工作,请发布您尝试的内容,我们会帮助您解决问题。 – Barmar

+0

我不确定,你想要的和命令行中的'2> stderr_file.txt'是一样的吗? 也许你需要在构建它之后通过linux脚本调用你的C++程序,或者甚至在你的调用之后创建和运行你的程序并添加'2>'的脚本。 –

回答

4

在C

#include <stdio.h> 

int 
main(int argc, char* argv[]) { 
    freopen("file.txt", "w", stderr); 

    fprintf(stderr, "output to file\n"); 
    return 0; 
} 

在C++

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 

int 
main(int argc, char* argv[]) { 
    ofstream ofs("file.txt"); 
    streambuf* oldrdbuf = cerr.rdbuf(ofs.rdbuf()); 

    cerr << "output to file" << endl; 

    cout.rdbuf(oldrdbuf); 
    return 0; 
} 
0

另一种方式做,这是一个具有以下dup2()呼叫

#include <iostream> 
#include <stdexcept> 
#include <stdio.h> 
#include <unistd.h> 

using std::cerr; 
using std::endl; 

int main() { 
    auto file_ptr = fopen("out.txt", "w"); 
    if (!file_ptr) { 
     throw std::runtime_error{"Unable to open file"}; 
    } 

    dup2(fileno(file_ptr), fileno(stderr)); 
    cerr << "Write to stderr" << endl; 
    fclose(file_ptr); 
} 
+0

最后它会将你的信息写入文件,对吧? –

+0

FirdavsbekNarzullaev是的 – Curious

相关问题