C Library - tmpfile() function



The C library FILE *tmpfile(void) creates a temporary file in binary update mode (wb+). The temporary file created is automatically deleted when the stream is closed (fclose) or when the program terminates.

Syntax

Following is the C library syntax of the tmpfile() function −

FILE *tmpfile(void);

Parameters

  • This function does not take any parameters.

Return Value

On success it returns a FILE* pointer to the newly created temporary file.On failure it returns NULL if the file could not be created. This could happen due to reasons such as insufficient file descriptors, lack of permission, or lack of temporary space.

Example 1: Creating and Writing to a Temporary File

This program creates a temporary file, writes a line of text to it, and then reads and prints the content of the file to the standard output.

Below is the illustration of the C library tmpfile() function.

#include <stdio.h>

int main() {
   FILE *temp = tmpfile();
   if (temp == NULL) {
       perror("Failed to create temporary file");
       return 1;
   }
   
   fprintf(temp, "This is a temporary file.\n");
   rewind(temp);
   
   char buffer[100];
   while (fgets(buffer, sizeof(buffer), temp) != NULL) {
       fputs(buffer, stdout);
   }
   
   fclose(temp);
   return 0;
}

Output

The above code produces following result−

This is a temporary file.

Example 2: Using Temporary File for Intermediate Computations

This program computes the square roots of numbers from 0 to 10, writes the results to a temporary file, and then reads and prints the results

#include <stdio.h>
#include <math.h>

int main() {
   FILE *temp = tmpfile();
   if (temp == NULL) {
       perror("Failed to create temporary file");
       return 1;
   }
   
   for (int i = 0; i <= 10; i++) {
       double value = sqrt(i);
       fprintf(temp, "%d %.2f\n", i, value);
   }
   rewind(temp);
   
   int num;
   double sqrt_value;
   while (fscanf(temp, "%d %lf", &num, &sqrt_value) != EOF) {
       printf("sqrt(%d) = %.2f\n", num, sqrt_value);
   }
   
   fclose(temp);
   return 0;
}

Output

After execution of above code, we get the following result −

sqrt(0) = 0.00
sqrt(1) = 1.00
sqrt(2) = 1.41
sqrt(3) = 1.73
sqrt(4) = 2.00
sqrt(5) = 2.24
sqrt(6) = 2.45
sqrt(7) = 2.65
sqrt(8) = 2.83
sqrt(9) = 3.00
sqrt(10) = 3.16
Advertisements