Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Sep 19th, 2004, 8:32 AM   #1
Siren201
Newbie
 
Join Date: Sep 2004
Posts: 1
Rep Power: 0 Siren201 is on a distinguished road
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
Siren201 is offline   Reply With Quote
Old Sep 19th, 2004, 9:41 AM   #2
Ashcroft
Programmer
 
Join Date: Sep 2004
Posts: 38
Rep Power: 0 Ashcroft is on a distinguished road
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);
  }
}
If the directory does exist then sb will contain information about it., if you need to tell if a file is a directory or a regular file or has specific permissions. Check the stat man page and sys/stat.h for all the stuff you can tell about a file and what the possible values of errno mean.
Ashcroft is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 2:38 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC