C++ tmpfile()

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

Overview

The C++ tmpfile() method creates and opens a temporary file with a unique auto-generated filename in binary read/write (wb+) mode. When the program calls fclose() or when the program terminates, the file will be automatically deleted. It is defined in \<cstdio> header file.

Syntax of tmpfile() in C++

Parameters of tmpfile() in C++

None i.e tmpfile() function in C++ does not take any argument.

Return Value of tmpfile() in C++

tmpfile() function in C++ returns one of the two values mentioned below:

  • It returns a stream pointer to the temporary file produced if it successfully creates that temporary file.
  • It returns null if it fails.

What is tmpfile() in C++?

tmpfile() method is used to create a temporary binary file in write/read mode. It is defined in the header file <cstdio>. It does take any argument and returns a stream pointer to the temporary file if open successfully otherwise returns Null. The temporary file created by tmpfile() is deleted after closing the stream object or if the program terminates so it is better to save the content of this file elsewhere if required.

Example

Below example explains how tmpfile() function in C++ works.

Output :

Explanation:

First, we have created a file pointer fptr and called tmpfile() function and also created a string write, if tmpfile() fails to create a file then it will return NULL so we have printed the error message, otherwise if tmpfile() works successfully then a new file gets created and we have written the string into the file using fputs(). To read data from the file we have used fgets() function and stored the file data into read array and displayed the output into the stdout and deleted the file using fclose() function.

Conclusion

  • C++ tmpfile() method creates and opens a temporary file with a unique auto-generated filename in binary read/write (wb+) mode.
  • If tmpfile() function works successfully then it returns stream pointer to the temporary file created.
  • If tmpfile() functions fails then it returns NULL.

See Also: