Pejman Moghadam / C-programming

C - Using Temporary Files

Public domain


Using mkstemp with UNIX I/O funtions (open, write, and so on)

If the temporary file is for internal use only and won't be handed to another program, it's a good idea to call unlink on the temporary file immediately. The unlink function removes the directory entry corresponding to a file, but because files in a file system are reference-counted, the file itself is not removed until there are no open file descriptors for that file, either. This way, your program may continue to use the temporary file, and the file goes away automatically as soon as you close the file descriptor. Because Linux closes file descriptors when a program ends, the temporary file will be removed even if your program terminates abnormally. -- Advanced Linux Programming

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h>

#define HELLO "Hello World !!!"
#define HELLO_SIZE 15

int main ()
{
  char *buffer;

  /* The last six characters of template 
   * must be "XXXXXX" and these are replaced 
   * with a string that makes the filename unique. 
   */
  char tmpfile[] = "/tmp/tmp.XXXXXX";
  int fd = mkstemp (tmpfile);

  /* Unlink the file immediately, so that it will be 
   * removed when the file descriptor is closed.  
   */ 
  unlink (tmpfile);

  /* Write to the temp file. */
  write (fd, HELLO, HELLO_SIZE);

  /* Rewind to the beginning of the temp file. */ 
  lseek (fd, 0, SEEK_SET);

  /* Allocate a buffer and read the data from the temp file. */ 
  buffer = (char*) malloc (HELLO_SIZE + 1);
  read (fd, buffer, HELLO_SIZE);

  /* Closing the file descriptor will cause the temporary file to remove */
  close (fd); 

  /* Add trailing null byte */
  *(buffer+HELLO_SIZE) = '\0';

  /* Write buffer to stdout */
  printf("%s", buffer);
}

Using tmpfile with C library's stream I/O functions (fopen, fprintf, and so on)

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h>

#define HELLO "Hello World !!!"
#define HELLO_SIZE 15

int main ()
{
  char *buffer;
  /* The temporary file will automaticly unlinked */
  FILE *fp = tmpfile();

  /* Write to the temp file. */
  fprintf(fp, HELLO); 

  /* Rewind to the beginning of the temp file. */ 
  rewind(fp);

  /* Allocate a buffer and read the data from the temp file. */ 
  buffer = (char*) malloc (HELLO_SIZE + 1);
  fgets(buffer, HELLO_SIZE + 1, fp);

  /* Closing the file descriptor will cause the temporary file to remove */
  fclose (fp);

  /* Write buffer to stdout */
  printf("%s", buffer);
}

BY: Pejman Moghadam
TAG: c, tmpfile, mkstemp
DATE: 2011-06-03 00:49:00


Pejman Moghadam / C-programming [ TXT ]