w3resource

C tmpfile() function

C library function - tmpfile()

The tmpfile() function is used to create a temporary file and open a corresponding stream. The file shall be automatically deleted when all references to the file are closed.

Note: The file shall be opened as in fopen() for update (wb+), except that implementations may restrict the permissions, either by clearing the file mode bits or setting them to the value S_IRUSR | S_IWUSR.

Syntax:

FILE *tmpfile(void);

Return value from tmpfile()

  • Upon successful completion, tmpfile() shall return a pointer to the stream of the file that is created.
  • Otherwise, it shall return a null pointer and set errno to indicate the error.

Example: tmpfile() function

The following example creates a temporary file for update, and returns a pointer to a stream for the created file in the fp variable.

#include <stdio.h>
int main () {
   FILE *fp;

   fp = tmpfile();
   printf("Temporary file created..!\n");

   /* Here you can use tmp file. */

   fclose(fp);

   return(0);
}

Output:

Temporary file created..!

Errors: The value of error number can be set to:

Value Meaning
EINTR A signal was caught during tmpfile().
EMFILE All file descriptors available to the process are currently open.
ENFILE The maximum allowable number of files is currently open in the system.
ENOSPC The directory or file system which would contain the new file cannot be expanded.
EOVERFLOW The file is a regular file and the size of the file cannot be represented correctly in an object of type off_t.
ENOMEM Insufficient storage space is available.

C Programming Code Editor:

Previous C Programming: C setvbuf()
Next C Programming: C tmpnam()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

Reading a string with scanf :

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

Ref : https://bit.ly/3pdEk6f