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>
The tmpfile()
function accepts no parameters.
tmpfile()
returns a pointer to the file upon its successful creation, otherwise it returns NULL
.
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 fileif(ptr == NULL){printf("The file pointer is NULL");return 0;}else{printf("The file has been created\n");}while(input[i] != '\0'){//writes to filefputc(input[i] , ptr);i++;}//positions pointer at the start of filerewind(ptr);// check for end of filewhile(!feof(ptr)){//reads from fileprintf("%c",fgetc(ptr));}}
ptr
ptr
for NULL
value to detect unsuccessful creation of the filefputc()
function writes one character of
“Educative.io” to the file at a time until the end of the string is reachedfgetc()
function reads one character at a time until the end of the file is reached as identified by feof()
Free Resources