perror
perror

Reputation: 7426

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.

Upvotes: 17

Views: 17967

Answers (2)

perror
perror

Reputation: 7426

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;
}

Upvotes: 8

Nemanja Boric
Nemanja Boric

Reputation: 22177

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!

Upvotes: 12

Related Questions