amza
amza

Reputation: 810

Redirecting stderr into a temp file

On windows I would use something like this:

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

But the man page for tempnam in linux specifically says not to use it and to use mkstemp instead. Fair enough. But it returns a file descriptor instead. Is there any easy way to use mkstemp to redirect stderr into the file? And also store the file name generated by mkstemp for future use in the program if necessary?

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

Upvotes: 0

Views: 381

Answers (2)

Mirar
Mirar

Reputation: 96

You want to look into dup2().

   dup2(fd,2);

should do the trick:

   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.

Source: man dup

Upvotes: 3

Nagendra NR
Nagendra NR

Reputation: 53

To Answer your second part of the question, to store the file name generated by mkstemp for future use in the program if necessary, just use a local variable to store the 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);

Upvotes: 0

Related Questions