How to create a temporary file in Linux

  • by

1.0 Temporary Files

Quite often, we need temporary files in our programs. Some intermediate data needs to be stored and the file can be discarded when the process terminates. There are functions and command to create temporary files in Linux. The mkstemp function creates a temporary file and returns a file descriptor. The mkdtemp function creates a temporary directory. The tmpfile function creates a temporary file and returns a file pointer. The mktemp command is for creating a temporary file or directory from the shell.

2.0 mkstemp

#include <stdlib.h>

int mkstemp (char *template);

mkstemp creates a unique temporary file, opens it and returns a file descriptor to it. The file is created from the parameter, template, whose last six characters must be "XXXXXX". mkstemp modifies the six X's to get a unique filename. Since the template is modified, it should not be a constant string. It should be a null terminated character array. The file is created with 0600 permissions, which means read and write permissions for the owner and none for the group and others. The file is opened with O_EXCL flag, which guarantees that the caller process has created the file.

As an example, we can use mkstemp to create a temporary file in code like this.

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

void error (char *str);

int main (int argc, char **argv)
{
    char filename [64] = "/tmp/mkstemp-example-XXXXXX";
    char buf [128];

    int fd;

    if ((fd = mkstemp (filename)) == -1)
        error ("mkstemp");
    unlink (filename);

    strcpy (buf, "Hello World!\n");

    if (write (fd, buf, strlen (buf)) == -1)
        error ("write");
}

void error (char *str)
{
    perror (str);
    exit (1);
}

The unlink call deletes the file. Since the file descriptor is in use, the file inode and data stay in the filesystem. When the process terminates, there is no link to the file and no process has it open, and so, it is deleted.

3.0 mkdtemp

#include <stdlib.h>

char *mkdtemp (char *template);

The mkdtemp function creates a temporary directory using the template. The last six characters of the template must be "XXXXXX". mkdtemp changes the X's in the template to generate a unique pathname. template is modified and must not be a constant string. It should be a null terminated character array. The directory is created with the permissions 0700. mkdtemp returns a pointer to the modified template on success and NULL on failure.

4.0 tmpfile

#include <stdio.h>

FILE *tmpfile (void);

The tmpfile function creates a temporary file. It returns a FILE pointer or NULL in case of error. The file is automatically opened for writing and is deleted when it is closed, or, when the calling process terminates. An example program using tmpfile is given below.

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

void error (char *str);

int main (int argc, char **argv)
{
    char buf [128];

    FILE *fp;

    if ((fp = tmpfile ()) == NULL)
        error ("tmpfile");

    strcpy (buf, "Hello World!\n");

    if (fwrite (buf, strlen (buf), 1, fp) != 1)
        error ("fwrite");
}

void error (char *str)
{
    perror (str);
    exit (1);
}

5.0 mktemp command

The mktemp command creates a temporary file or directory and prints its name. The command usage is,

mktemp [OPTION]... [TEMPLATE]

The TEMPLATE is a character string containing at least 3 consecutive X's at the end. The X's are modified to get a unique file name. The important options are -d to create a temporary directory and not a file and --tmpdir[=DIR]. With the tmpdir option, the TEMPLATE is interpreted with respect to the DIR specified with tmpdir. If tmpdir is specified without the DIR, the directory in the environment variable $TMPDIR is used and if $TMPDIR is not set /tmp is used.

If TEMPLATE is not specified then a default TEMPLATE value tmp.XXXXXXXXXX is used and the option --tmpdir is implied. Some examples of using mktemp are given below. The environment variable $TMPDIR is not set.

$ # make a temp file with file name starting with "abc" 
$ # and three other characters in the current directory
$ mktemp abcXXX
abc2nD
$ # make a temp file in /tmp
$ mktemp 
/tmp/tmp.Xzt1K9T2Fk
$ # make a temp directory
$ mktemp -d mytempdirXXX
mytempdir7GH
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You may like these, also

  • POSIX message queues in LinuxPOSIX message queues in Linux 1.0 POSIX Message queues POSIX interprocess comunication (IPC) was introduced in the POSIX.1b standard (IEEE Std 1003.1b-1993) for real time…
  • POSIX Shared Memory in LinuxPOSIX Shared Memory in Linux 1.0 Shared Memory Shared memory is the fastest method of interprocess communication (IPC) under Linux and other Unix-like systems. The…
  • POSIX Semaphores in LinuxPOSIX Semaphores in Linux 1.0 Semaphores Semaphores are used for process and thread synchronization. Semaphores are clubbed with message queues and shared memory under…
  • fork and exec system calls in Linuxfork and exec system calls in Linux 1.0 fork and exec system calls Suppose we wish to write a "shell program" which would execute another program. Now,…
  • Connecting two computers with Ethernet LAN cableConnecting two computers with Ethernet LAN cable Quite often, we wish to connect two computers back to back using an Ethernet LAN cable. It may be because…
  • D-Bus TutorialD-Bus Tutorial 1.0 D-Bus D-Bus is a mechanism for interprocess communication under Linux and other Unix-like systems. D-Bus has a layered architecture.…
  • Socket programming using the select system callSocket programming using the select system call 1.0 Client-Server Paradigm The Client-Server paradigm divides the software architecture of a system in two parts, the server and its…
  • System V message queues in LinuxSystem V message queues in Linux 1.0 Message queues Message queues are one of the interprocess communication mechanisms available under Linux. Message queues, shared memory and…
  • POSIX Threads Synchronization in CPOSIX Threads Synchronization in C 1.0 POSIX Threads Synchronization POSIX Threads provide multiple flows of execution within a process. The threads have their own stacks…
  • System V Shared Memory in LinuxSystem V Shared Memory in Linux 1.0 Shared Memory Shared memory is one of the three interprocess communication (IPC) mechanisms available under Linux and other Unix-like…