tags:

views:

131

answers:

2

Hi,

How can i create a temporary folder in /tmp directory.

+2  A: 

Try the mkdtemp function.

char *tmpdir;
strcpy (template, "/tmp/myprog.XXXXXX");
tmpdir = mkdtemp (template);

if (!tmpdir) {
    // Error out here
}

printf ("Temporary directory created : %s", tmpdir);
Tim Kane
"The mkdtemp() function generates a uniquely-named temporary directory from template. The last six characters of template must be XXXXXX and these are replaced with a string that makes the directory name unique." -- the question didn't ask for these specifications
Sev
@Sev: nor discarded. The OP still can use `mkdir` if he doesn't care about unique naming. IMO, launching a process to only create a directory is kinda exaggerated.
jweyrich
you're right on the money there
Sev
@Tim: would you update your example to assign the return value to a variable? We get the idea, but the OP might not (no disrespect here).I find important to mention about `mkdir` too.
jweyrich
A: 

Since I can't change/improve other's answers yet, I'm writing one myself.

I'd use stat and mkdir. For example:

#include <errno.h> // for errno
#include <stdio.h> // for printf
#include <stdlib.h> // for EXIT_*
#include <string.h> // for strerror
#include <sys/stat.h> // for stat and mkdir

int main() {
    const char *mydir = "/tmp/mydir";
    struct stat st;
    if (stat(mydir, &st) == 0) {
        printf("%s already exists\n", mydir);
        return EXIT_SUCCESS;
    }
    if (mkdir(mydir, S_IRWXU|S_IRWXG) != 0) {
        printf("Error creating directory: %s\n", strerror(errno));
        return EXIT_FAILURE;
    }
    printf("%s successfully created\n", mydir);
    return EXIT_SUCCESS;
}
jweyrich