C++ tmpfile()

Build an AI-First Career, Master the Complete Skillset
Choose from our industry-leading programs designed for career success
Modern Software and AI Engineering Program
Master full-stack development with AI integration
+1000 moreModern Data Science and ML with specialisation in AI
Advanced data science techniques with AI specialization
+1000 moreAdvanced AIML with Specialisation in Agentic AI
Deep dive into AIML with focus on Agentic systems
+1000 moreDevOps, Cloud & AI Platform Engineering
Build and manage AI-powered cloud infrastructure
+1000 moreAI Engineering Advanced Certification by IIT-Roorkee
Premier AI engineering certification from IIT-Roorkee
AI Forward Deployed Engineer Program
Full-stack engineering, production AI and client-facing consulting
+1000 moreOverview
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.
How Scaler Transformed Careers in Different Fields
Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.
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.
Turn Learning into Career Growth
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.