Answer: Sometimes, a program can use a file to hold data temporarily. This file is deleted automatically when program is finished or we can explicitly close the file using ‘fclose()’ when it’s no longer required. The ‘tmpfile()’ function opens a unique temporary file in binary read/write (w+b) mode. It’s prototyped below
FILE * tmpfile(void);
‘tmpfile()’ can’t be used to open file in different mode other than “wb+”. Use ‘fopen()’ for any such requirements. Following is prototyped ‘tmpnam()’ function
char *tmpnam(char *name);
used to construct unique name for temporary file. Name constructed doesn’t conflict with any existing name. Remember that if tmpnam() is called with NULL argument, function returns a pointer to static array holding the unique name otherwise constructs the name into the array and returns pointer to it. Aarray must be L_tmpnam characters long and ‘tmpnam()’ can construct upto TMP_MAX times unique names when it’s called repeatedly. Let’s experiment with ‘tmpfile()’ and ‘tmpname()’ functions below,
/* tmpfile.c -- program creates a file to hold data temporarily */ /* FILE *tmpfile(void) */ #include <stdio.h> #include <stdlib.h> #define NAME_SIZE L_tmpnam #define BUF_SIZE 1000 int main(void) { long cp; FILE *tfile; char tf_name[NAME_SIZE]; char buffer[BUF_SIZE]; /* let's create and open a temporary file */ tfile = tmpfile(); /* verify if file created and opened successfully */ if (tfile == NULL) { perror("temporary File Created: "); exit(1); } /* deleting the temporary file */ close(tfile); /* tmpnam() function constructs name suitable for temporary file */ tmpnam(tf_name); printf("Temporary File Name Constructed: %s\n", tf_name); /* open temporary file using fopen() */ tfile = fopen("tf_name", "wb+"); /* if file opened successfully */ if (tfile == NULL) { perror("Temporary File Open: "); exit(2); } /* let's attempt to write to temporary file */ fprintf(tfile, "%s", "temporary file: are you there?"); fflush(tfile); cp = ftell(tfile); printf("Current Position in Temporary File: %ld\n", cp); /* Set to the beginning in Temporary File */ rewind(tfile); cp = ftell(tfile); printf("Changed Position in Temporary File: %ld\n", cp); fgets(buffer, BUF_SIZE, tfile); printf("Read from temporary file : \"%s\"\n", buffer); return 0; }
Output of the program follows
Temporary File Name Constructed: /tmp/filejw3p8g Current Position in Temporary File: 30 Changed Position in Temporary File: 0 Read from temporary file : "temporary file: are you there?"
Simply put, we created a temporary file then wrote something to it, then changed position to the beginning in the file and then finally read what we had written to it!
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Check Computer Science Books
- Practice BCA MCQs
- Apply for C Internship
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs