简体   繁体   中英

How to create a temporary directory in C?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM