【问题标题】:Redirecting stderr into a temp file将stderr重定向到临时文件
【发布时间】:2015-07-24 16:32:15
【问题描述】:

在 Windows 上我会使用这样的东西:

strcpy (errorFileName, _tempnam (NULL,"pfx"));
freopen (errorFileName, "wt", stderr);

但 linux 中 tempnamman page 明确表示 使用它并改为使用 mkstemp。很公平。但它会返回一个文件描述符。有没有简单的方法可以使用mkstempstderr 重定向到文件中?并且存储mkstemp生成的文件名,以备将来在程序中使用?

int fd = mkstemp("pfxXXXXXX");
if (fd != -1)
{
    //get file name here? or is there a better way
    strcpy (errorFileName, nameFromFd);
    freopen (errorFileName, "wt", stderr);
}

【问题讨论】:

  • 为什么不让用户决定他想在哪里看到他的输出?
  • @BaummitAugen 他们确实决定,这是仅在他们指定选项时才执行的方法的一部分。不管怎样,这不是我的代码。我不能做出那样的设计决定。
  • 我的意思是用户可以根据需要从程序外部重定向stderr,因此无需在您的代码中执行此操作。
  • 如果你真的想在你的程序中这样做,只需使用一个变量:FILE* output = b?stderr:tmpfile("log") 并写入output 而不是stderr。会比修改全局状态更清晰。
  • 由于您似乎在使用 C++,请删除 C 标签。这些是不同的语言,解决方案可能是特定的。

标签: c++ c unix stderr io-redirection


【解决方案1】:

您想查看 dup2()。

   dup2(fd,2);

应该做的伎俩:

   int dup2(int oldfd, int newfd);

   dup2() makes newfd be the copy of oldfd, closing newfd first if  neces-
   sary, but note the following:

   *  If  oldfd  is  not a valid file descriptor, then the call fails, and
      newfd is not closed.

   *  If oldfd is a valid file descriptor, and newfd has the same value as
      oldfd, then dup2() does nothing, and returns newfd.

资料来源: man dup

【讨论】:

  • 如果您显示的文档是一个引用(如格式所示),您应该添加一个来源,可能是一个链接。
  • 确保这是您在程序中做的第一件事。对*FILE 和文件描述符的混合操作可能会导致奇怪的结果。
  • Source 是 dup/dup2/dup3 的手册页,这是在 unix 系统上查找 C 库函数的常规方法。 “man dup2”会给你这些信息。
【解决方案2】:

要回答您的第二部分问题,如果需要存储 mkstemp 生成的文件名以供将来在程序中使用,只需使用局部变量来存储文件名

char nameBuff[32];
memset(nameBuff,0,sizeof(nameBuff));
strncpy(nameBuff,"/tmp/myTmpFile-XXXXXX",21);
mkstemp(nameBuff);
printf("\n Temporary file [%s] created\n", nameBuff);

【讨论】:

    猜你喜欢
    • 2014-07-22
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 2019-06-14
    • 2021-06-29
    • 2011-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多