Creating Unique Temporary Files in C using mkstemp

There are multiple ways of creating unique temporary files in C, namely tempnam, tmpfile, mkstemp. mkstemp and tmpfile are more secure than tempnam. mkstemp additionally lets you specificy a template for the file name and the directory in which these temporary files should be created. Here’s a code snippet which uses mkstemp to create temporary files in the /tmp directory.

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

#define TEMPLATE_NAME "CLIXXXXXX"       /*Template Name*/
#define TEMPLATE_DIR "/tmp"             /*Directory*/

int main (void) {
    char *template;
    int templateSize, dirSize;
    int fd;

    templateSize  = strlen( (const char *) TEMPLATE_NAME );
    dirSize =  strlen( (const char *) TEMPLATE_DIR );
    template = (char *) malloc ((size_t) ((sizeof(char)) * (templateSize + dirSize + 2)));
    strncpy(template, (const char *) TEMPLATE_DIR, dirSize);
    strncpy(template + dirSize, (const char *) "/", (int) 1);
    strncpy(template + dirSize + 1, (const char *) TEMPLATE_NAME, templateSize);
    template[dirSize + 1 + templateSize] = '\0';
    if ((fd = mkstemp (template)) < 0 ) {
        return -1;
    } else {
        printf("filename - %s\n", template);
    return 0;
The template name should always end with the six characters XXXXXX

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.