【问题标题】:How to redirect stderr to file without any buffer?如何将stderr重定向到没有任何缓冲区的文件?
【发布时间】:2017-12-06 12:06:21
【问题描述】:

有人知道如何在不缓冲的情况下将 stderr 重定向到文件中吗?如果可能的话,你能给我看一个用于 linux (Centos 6) 操作系统的 c++ 语言的简单代码吗?!

【问题讨论】:

  • stderr 默认情况下不缓冲。
  • SO 不是免费的编码服务。您必须自己尝试解决问题。如果您无法使其正常工作,请发布您尝试过的内容,我们会帮助您解决问题。
  • 我不确定,你想要的和命令行中的2> stderr_file.txt 一样吗?也许您需要的是在构建它之后通过 linux 脚本调用您的 C++ 程序,或者甚至制作构建和运行您的程序的相同脚本,在您调用之后添加 2>
  • 您应该针对特定问题提出特定问题。由于 Stack Overflow 向您隐藏了关闭原因:“要求我们推荐或查找书籍、工具、软件库、教程或其他非现场资源的问题对于 Stack Overflow 来说是无关紧要的,因为它们往往会吸引固执己见的答案和垃圾邮件。相反,请描述问题以及迄今为止为解决该问题所做的工作。"
  • 我怀疑操作系统缓存管理器是否允许您无缓冲地写入。您可能需要采取额外的步骤来刷新重定向。

标签: c++ linux centos6


【解决方案1】:

在 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;

  cerr.rdbuf(oldrdbuf);
  return 0;
}

【讨论】:

  • 不应该是cerr.rdbuf(oldrdbuf);吗?
【解决方案2】:

另一种方法是使用以下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);
}

【讨论】:

  • 最后它会将你的消息写入文件,对吗?
  • FirdavsbekNarzullaev 是的
猜你喜欢
  • 2014-09-30
  • 2015-11-10
  • 2014-07-22
  • 2013-10-19
  • 2011-02-06
  • 1970-01-01
  • 1970-01-01
  • 2012-06-16
  • 1970-01-01
相关资源
最近更新 更多