在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);
}
答案 0 :(得分:3)
您想要查看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
答案 1 :(得分:0)
要回答问题的第二部分,如果需要,存储由mkstemp生成的文件名以备将来在程序中使用,只需使用局部变量来存储fileName
char nameBuff[32];
memset(nameBuff,0,sizeof(nameBuff));
strncpy(nameBuff,"/tmp/myTmpFile-XXXXXX",21);
mkstemp(nameBuff);
printf("\n Temporary file [%s] created\n", nameBuff);