Creating temporary files with tmpfile
What you'll learn: How to use the tmpfile() function to create a secure, self-destructing scratchpad for your program's data.
The Scratchpad Concept
Imagine you are working on a complex math problem. You have your final answer sheet, but you also need a piece of "scratch paper" to perform intermediate calculations. Once the problem is solved, you crumple up that scratch paper and throw it away; it was never meant to be permanent.
In C, tmpfile() provides exactly this. It creates a temporary file that exists only as long as your program needs it. The moment you close the file or your program finishes running, the file vanishes from your hard drive automatically.
Why use tmpfile?
You might wonder, "Why not just create a regular file named temp.txt?"
Using tmpfile() is superior for two reasons:
- Security: The system generates a unique, unpredictable name, preventing other programs from easily guessing or interfering with your data.
- Cleanliness: You don't have to worry about manually deleting files. If your program crashes, the operating system generally handles the cleanup for you.
Using tmpfile in C
The tmpfile() function lives in <stdio.h>. It takes no arguments and returns a standard FILE pointer, just like fopen(). The file is automatically opened in wb+ mode (binary read/write).
#include <stdio.h>
int main() {
// Create the temporary file
FILE *temp_ptr = tmpfile();
if (temp_ptr == NULL) {
printf("Unable to create temporary file.\n");
return 1;
}
// Use it like any other file
fprintf(temp_ptr, "Temporary data: 42");
// Rewind to read from the start
rewind(temp_ptr);
char buffer[50];
fgets(buffer, 50, temp_ptr);
printf("Read from temp: %s\n", buffer);
// Closing the file deletes it from the system
fclose(temp_ptr);
return 0;
}
Important Considerations
Because tmpfile() handles the filename and location for you, you cannot "find" this file in your file explorer while the program is running—it is often hidden or stored in a restricted system directory. Additionally, remember that tmpfile() opens the file in "update" mode. If you write data and want to read it back, you must use rewind() or fseek() to move the file pointer back to the beginning.
Key takeaway
tmpfile() creates a secure, temporary file stream that automatically deletes itself when closed or when the program terminates.