【发布时间】:2015-07-24 16:32:15
【问题描述】:
在 Windows 上我会使用这样的东西:
strcpy (errorFileName, _tempnam (NULL,"pfx"));
freopen (errorFileName, "wt", stderr);
但 linux 中 tempnam 的 man page 明确表示 不 使用它并改为使用 mkstemp。很公平。但它会返回一个文件描述符。有没有简单的方法可以使用mkstemp 将stderr 重定向到文件中?并且还存储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