mkostemp(), mkostemps()

Updated: April 19, 2023

Make a unique temporary filename and open the file, specifying some flags

Synopsis:

#include <stdlib.h>
#include <fcntl.h>

int mkostemp( char* template,
              int oflags );

int mkostemps( char *template,
               int slen,
               int oflags );

Arguments:

template
A template for the filename that you want to use. For mkostemp(), this template can be any file name with at least six X characters appended to it (for example, /tmp/temp.XXXXXX); for mkostemps(), it also includes a suffix (e.g., /tmp/temp.XXXXXXsuffix).
slen
(mkostemps() only) The length of the suffix included in the template.
oflags
Zero or more of the following flags for the underlying open():
  • O_APPEND — append on each write.
  • O_CLOEXEC — set the close-on-exec flag on the new file descriptor.
  • O_DSYNC — subsequent I/O waits until all data is successfully transferred to the storage device.
  • O_LARGEFILE — allow the file offset to be 64 bits long.
  • O_RSYNC — read I/O operations on the file descriptor complete at the same level of integrity as specified by O_DSYNC and O_SYNC.
  • O_SYNC — perform synchronous I/O operations.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The mkostemp() and mkostemps() functions take the given file name template and overwrite a portion of it to create a filename.

The generated file name is unique and suitable for use by the application. The Xs are replaced with the current process number and/or a unique letter combination. The number of unique file names that these functions can return depends on the number of Xs provided; the functions try at least 231 combinations before giving up.

The mkostemp() and mkostemps() functions (unlike mktemp()) create the template file, mode 0600 (i.e., read-write for the owner), returning a file descriptor opened for reading and writing. This avoids the race between testing for a file's existence and opening it for use.

Returns:

The file descriptor of the temporary file, or -1 if no suitable file could be created (errno is set).

Errors:

EINVAL
One of the following:
  • The template doesn't include at least six X wildcard characters, or (for mkostemps()) the length of the template is less than slen.
  • The flags argument is invalid.
EEXIST
All the names tried already exist. Consider adding more wildcard characters to the template.

This function may also set errno to any value specified by open().

Classification:

OpenBSD

Safety:  
Cancellation point Yes
Interrupt handler No
Signal handler Yes
Thread Yes