How to use tempfile() in C

The tmpfile() function in C creates a temporary file that is automatically deleted when the program terminates.

The created file opens in binary update (wb+) mode.

To use the tmpfile() function, the program needs to include the stdio.h header file as shown below:

#include <stdio.h>

Parameters and Return Value

The tmpfile() function accepts no parameters.

tmpfile() returns a pointer to the file upon its successful creation, otherwise it returns NULL.

Examples

The following code demonstrates how to create a temporary file, read from it, and write to a temporary file:

#include <stdio.h>
int main()
{
FILE* ptr;
ptr = tmpfile();
char input[] = "Educative.io";
int i = 0;
//checks for successful creation of file
if(ptr == NULL)
{
printf("The file pointer is NULL");
return 0;
}
else
{
printf("The file has been created\n");
}
while(input[i] != '\0')
{
//writes to file
fputc(input[i] , ptr);
i++;
}
//positions pointer at the start of file
rewind(ptr);
// check for end of file
while(!feof(ptr))
{
//reads from file
printf("%c",fgetc(ptr));
}
}

Explanation

  • In the above example, a temporary file is created and stored in the pointer ptr
  • The program checks ptr for NULL value to detect unsuccessful creation of the file
  • The fputc() function writes one character of “Educative.io” to the file at a time until the end of the string is reached
  • The fgetc() function reads one character at a time until the end of the file is reached as identified by feof()
Copyright ©2024 Educative, Inc. All rights reserved