![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Sep 2004
Posts: 1
Rep Power: 0
![]() |
Hi
Just wondering if anyone know how to a) Check if a directory exists b) Create it if it does'nt This is in unix using C I tried creating the directory using execlp("mkdir" , dirName) but that did'nt work. Besides I actually need a way of checking if it exists first. Cheers |
|
|
|
|
|
#2 |
|
Programmer
Join Date: Sep 2004
Posts: 38
Rep Power: 0
![]() |
You don't really have to do both those things seperately.
You can do the following #include <sys/types.h>
#include <sys/stat.h>
const char *dir_name = "foo";
mode_t mode = 0755;
if (mkdir(dir_name, mode) == -1) {
/* -1 on error, check errno for exact error */
if (errno == EEXIST) {
printf("directory already exists\n");
}
}If you have to check if a file exists as an operation seperate from creating it you can use stat. #include <sys/types.h>
#include <sys/stat.h>
const char *dir_name = "foo";
struct stat sb;
if (stat(dir_name, &sb) == -1) {
if (errno == ENOENT) {
printf("directory does not exist\n");
}
} else {
/* verify that it is a directory, the name exists but it might be a regular file */
if ((sb.st_mode & S_IFDIR) != S_IFDIR) {
printf("%s exists but is not a directory\n", dir_name);
}
} |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|