A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
tmpfile creates a temporary file opened in "wb+" mode (read and write, binary). The file is automatically deleted when you close it or when the program exits normally. You never see the filename. You never clean it up. It is the cleanest way to get scratch storage on disk without littering the filesystem with orphaned temp files.
#include <stdio.h>#include <string.h>int main(void) {FILE *tmp = tmpfile();if (tmp == NULL) {perror("tmpfile");return 1;}fputs("Temporary data line 1\n", tmp);fputs("Temporary data line 2\n", tmp);rewind(tmp);char buf[64];while (fgets(buf, sizeof(buf), tmp) != NULL) {printf("Read back: %s", buf);}fclose(tmp);printf("Temp file deleted automatically.\n");return 0;}
The file exists on disk while the program runs. You can write megabytes to it, seek around, read it back. When fclose is called, the OS removes the file. If the program crashes, the file might persist depending on the OS, but under normal operation, cleanup is automatic. This is useful for sorting large datasets that do not fit in RAM, for caching intermediate computation results, or for building data that will be renamed to a final destination.
tmpfile is not available on all embedded platforms, and some restricted environments (containers with read-only /tmp, sandboxed processes) may cause it to fail. Always check the return value. On Windows, the file is created in the directory specified by the TMP environment variable.
tmpfile eliminates an entire class of cleanup bugs. No forgotten unlink calls. No stale files accumulating in /tmp. If you need a filename (for passing to another process), use tmpnam instead, which we cover in the standard library module. Next: feof, and why using it as a loop condition is almost always wrong.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.