Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ <cstdio> tmpfile() function creates and opens a temporary file with a filename guaranteed to be different from any other existing file. The file is opened as a binary file for update (as by fopen() function with access mode "wb+").

If the program closes the file, e.g. by executing fclose(), the file is automatically deleted. If the program terminates normally, all files opened by calling tmpfile() are also automatically deleted. If the program terminates abnormally, whether the file is deleted depends on the specific system and library implementation.

Syntax

FILE* tmpfile();

Parameters

No parameter is required.

Return Value

On success, returns the associated file stream. On failure, NULL is returned.

Example:

The below example shows the usage of tmpnam() function.

#include <cstdio>
 
int main (){

  char str[100] = "Hello World!.";
  char mystring[100];

  //creating a temporary file
  FILE * tFile = tmpfile();

  //display message if file is not created
  if (tFile == NULL) {
    puts("Unable to create temporary file.");
    return 0;
  }
  
  //display message when the file is created
  puts("Temporary file is created.");

  //write str in the file
  fputs(str, tFile);

  //sets the file pointer at the 
  //beginning of the stream
  rewind(tFile);
  
  //display the content of the file
  fgets(mystring , 100 , tFile);
  printf("It contains: %s\n", mystring);

  //close the file
  fclose (tFile);

  return 0;
}

The output of the above code will be:

Temporary file is created.
It contains: Hello World!.

❮ C++ <cstdio> Library

5