How to create a temporary directory in C? How to create a temporary directory in C? unix unix

How to create a temporary directory in C?


You should use mkdtemp function.

#define  _POSIX_C_SOURCE 200809L#include <stdlib.h>#include <unistd.h>#include <stdio.h>int main(){        char template[] = "/tmp/tmpdir.XXXXXX";        char *dir_name = mkdtemp(template);        if(dir_name == NULL)        {                perror("mkdtemp failed: ");                return 0;        }        /* Use it here */        printf("%s", dir_name);        /* Don't forget to delete the folder afterwards. */        if(rmdir(dir_name) == -1)        {                perror("rmdir failed: ");                return 0;        }        return 0;}

Don't forget to delete the directory afterwards!


I suggest to use the mkdtemp() function together with usual functions from the C API (glibc). Here is a full answer:

EDIT: The answer from Nemanja Boric is unfortunately not usable in practice because the rmdir() function is only intended to remove an empty directory. Here is a full correct answer:

#define  _POSIX_C_SOURCE 200809L#define  _XOPEN_SOURCE 500L#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <errno.h>#include <ftw.h>/* Call-back to the 'remove()' function called by nftw() */static intremove_callback(const char *pathname,                __attribute__((unused)) const struct stat *sbuf,                __attribute__((unused)) int type,                __attribute__((unused)) struct FTW *ftwb){  return remove (pathname);}intmain (){  /* Create the temporary directory */  char template[] = "/tmp/tmpdir.XXXXXX";  char *tmp_dirname = mkdtemp (template);  if (tmp_dirname == NULL)  {     perror ("tempdir: error: Could not create tmp directory");     exit (EXIT_FAILURE);  }  /* Change directory */  if (chdir (tmp_dirname) == -1)  {     perror ("tempdir: error: ");     exit (EXIT_FAILURE);  }  /******************************/  /***** Do your stuff here *****/  /******************************/  /* Delete the temporary directory */  if (nftw (tmp_dirname, remove_callback, FOPEN_MAX,            FTW_DEPTH | FTW_MOUNT | FTW_PHYS) == -1)    {      perror("tempdir: error: ");      exit(EXIT_FAILURE);    }  return EXIT_SUCCESS;}