Archived:Creating temporary files in Open C
Programs often need to create temporary files just for the life time of the program. In Open C tmpnam() and tempfile() functions exist to assist in this task.
- tmpnam() generates file names that can be used for a temporary file.
- tmpfile() creates a temporary file and opens a corresponding stream to the created file.
The tmpnam() and tmpfile() functions return a pointer to a file name on success or NULL pointer in case of an error.
Note: In order to use this code, you need to install the Open C plug-in.
This snippet can be self-signed.
The following libraries are required:
#include <stdio.h> //fprintf, tmpnam, tmpfile, FILE
#include <sys/stat.h> //S_IWUSR
int main (void)
char *tmp_pathname = 0;
FILE *tmp_fileptr = 0;
FILE *tmp_filestream = 0;
/* create the tmp directory */
/* - tmpnam - */
if (!(tmp_pathname = tmpnam(NULL)))
perror("Error creating temporary filename!");
fprintf(stdout, "Temporary pathname %s\n", tmp_pathname);
if (!(tmp_fileptr = fopen(tmp_pathname, "w")))
perror("Error opening temporary file");
/* - tmpfile - */
if (!(tmp_filestream = tmpfile()))
perror("Error generating temporary stream!");
/* write to temporary file */
fprintf(tmp_filestream, "Temporary stream created by PID[%ld]", (long)getpid());
/* read from temporary file */
fgets(buffer, 100, tmp_filestream);
fprintf(stdout, "Temporary stream: %s\n", buffer);
Two temporary files are created. The tmpfile() created file is automatically deleted by the OS when all references to the file are closed.