📁Beginner

Create a Temporary File

Temporary file creation

Create a temporary file using tmpfile(). It is automatically deleted when closed or program ends.

Program Code

temp_file.c
C
1#include <stdio.h>
2
3int main() {
4 FILE *temp = tmpfile();
5
6 if (temp == NULL) {
7 printf("Error creating temp file!\n");
8 return 1;
9 }
10
11 // Write to temp file
12 fprintf(temp, "This is temporary data\n");
13 fprintf(temp, "Line 2 of temp file\n");
14
15 // Read back (seek to beginning first)
16 rewind(temp);
17
18 char buffer[100];
19 printf("Contents of temp file:\n");
20 while (fgets(buffer, sizeof(buffer), temp)) {
21 printf("%s", buffer);
22 }
23
24 // File automatically deleted when closed
25 fclose(temp);
26 printf("\nTemp file closed and deleted.\n");
27
28 return 0;
29}
Output

Contents of temp file:

This is temporary data

Line 2 of temp file

 

Temp file closed and deleted.

Want to Learn More?

Explore our comprehensive tutorials for in-depth explanations of C programming concepts.

Browse Tutorials
Back to All Examples