6

tmpfile () functions says that:

The temporary file created is automatically deleted when the stream is closed (fclose) or when the program terminates normally. If the program terminates abnormally, whether the file is deleted depends on the specific system and library implementation."

tmpfile () function returns a stream pointer to the temporary file created and not the path of file. I need temporary filename path as it needed to pass other library function.

My application can exit abnormally so tmpfile () function can work here on abnormal exit.

How can I get the temporary file path and file automatically delete on exit

1 Answers1

1

Instead of using tmpfile(), you could use tmpnam().

It will return a filename that can be used to create a temporary file.

See the following example (extracted from http://www.cplusplus.com/reference/cstdio/tmpnam/) :

#include <stdio.h>

int main ()
{
   char buffer [L_tmpnam];
   char *pointer;

   tmpnam (buffer);
   printf ("Tempname #1: %s\n", buffer);

   pointer = tmpnam (NULL);
   printf ("Tempname #2: %s\n", pointer);

   return 0;  
}

You can then use this filename to create your file and delete it upon exit.

Edit:

  • The name return by tmpnam doesn't specify any path. The default path used by fopen will be your current working directory.

  • It is up to you to delete the file. It will not be done automatically. You can do it by calling remove.

luator
  • 4,769
  • 3
  • 30
  • 51
G. Toupin
  • 54
  • 4