Name

mkstemp - creates a unique temporary file

Library

libc.lib

Synopsis

  #include <unistd.h>
  int mkstemp (char *template);

Return values

The mkstemp function returns -1 if no suitable file could be created and an error code is placed in the global variable. errno.

Detailed description

The mkstemp function takes the given file name template and overwrites a portion of it to create a file with that name and returns a file descriptor opened for reading and writing. This file name is guaranteed not to exist at the time of function invocation and is suitable for use by the application. The template may be any file name with some number of X s’ appended to it, for example /tmp/temp.XXXXXX. The trailing X s’ are replaced with a unique alphanumeric combination. The number of unique file names mkstemp can return depends on the number of X s’ provided; six X s’ will result in mkstemp selecting one of 56800235584 (62 ** 6) possible temporary file names.


Examples

#include <stdlib.h>
#include <stdio.h> //printf, SEEK_SET
#include <unistd.h>
 
int main( void )
{
 char arr[] = "c:\\someXXXXXXXX";
 char buf[10];
  
 //create a temporary file using mkstemp()
 int fd = mkstemp(arr);
  
 if(fd != -1)
 {
    //write to the file
    write(fd, "hello", 5);
    //seek to the beginning of the file
    lseek(fd, 0, SEEK_SET); //beg of the file
    //read from the file
    read(fd, buf, 5);
    buf[5] = '\0';
    //close the file
    close(fd);
 }
 
 printf("buf read: %s", buf);
 return 0;
}


Output

buf read: hello


Errors

The mkstemp function may set errno to one of the following values:
[ENOTDIR]
  The pathname portion of the template is not an existing directory.

The mkstemp function may also set errno to any value specified by the stat function.

The mkstemp function may also set errno to any value specified by the open function.


Notes

A common problem that results in a core dump is that the programmer passes in a read-only string to mkstemp, This is common with programs that were developed before -isoC compilers were common. For example, calling mkstemp with an argument of "/tmp/tempfile.XXXXXX" will result in a core dump due to mkstemp attempting to modify the string constant that was given. If the program in question makes heavy use of that type of function call,there is the option of compiling the program so that it will store string constants in a writable segment of memory.

See also

chmod, getpid, mkdir, open, stat
                                                                                                                                                        

Feedback

For additional information or queries on this page send feedback

© 2008 Nokia Corporation. All rights reserved. This documentation can be used in the connection with this Product to help and support the user.

Top