cunixglibc

How to create a temporary directory in C in Linux?


I am trying to create a temporary directory to perform some operations in it and then delete the whole thing at the end. I use C language in a UNIX system, so I would like to have some compliance with this environment.

What is the best way to program this ?

EDIT I really need a directory, not only a file. The small program is intended to try out if I can perform an svn checkout of a project. So, it should be able to create a full hierarchy of files and directories.


Solution

  • 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 <err.h>
    #include <ftw.h>
    
    /* Call-back to the 'remove()' function called by nftw() */
    static int
    remove_callback(const char *pathname,
                    __attribute__((unused)) const struct stat *sbuf,
                    __attribute__((unused)) int type,
                    __attribute__((unused)) struct FTW *ftwb)
    {
      return remove (pathname);
    }
    
    int
    main ()
    {
      /* Create the temporary directory */
      char template[] = "/tmp/tmpdir.XXXXXX";
      char *tmp_dirname = mkdtemp (template);
    
      if (tmp_dirname == NULL)
        err (EXIT_FAILURE, "mkdtemp: error: Cannot create tmp directory");
    
      /* Change directory */
      if (chdir (tmp_dirname) == -1)
        err (EXIT_FAILURE, "chdir: error");
    
      /******************************/
      /***** Do your stuff here *****/
      /******************************/
    
      /* Delete the temporary directory */
      if (nftw (tmp_dirname, remove_callback, FOPEN_MAX,
                FTW_DEPTH | FTW_MOUNT | FTW_PHYS) == -1)
        err (EXIT_FAILURE, "tempdir: error");
    
      return EXIT_SUCCESS;
    }