santoshv25
asked on
Check whether a directory exists
I am writing a c program
in which i am accepting command parameter as directoyr name
and i want to check whether that directory exists.
how to check through the program ?? only using system command ?
any other alternative ?
thanks
in which i am accepting command parameter as directoyr name
and i want to check whether that directory exists.
how to check through the program ?? only using system command ?
any other alternative ?
thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You can use chdir() if you are using Boraland COmpilers(turboc++ or Borland C++)
You require dir.h for this.
chdir returns an int.
If directory doesnt exist,it returns -1 and sets errno to ENOENT.
You require dir.h for this.
chdir returns an int.
If directory doesnt exist,it returns -1 and sets errno to ENOENT.
u can use _access() too it returns ENOENT Filename or path not found.
Another method, if you are on windows/MSVC.
DWORD FA = GetFileAttributes(path);
if (FA != (DWORD) -1) {
// The path exists
if (FA & FILE_ATTRIBUTE_DIRECTORY) {
// It's a directory
}
}
But the truth is that there are a number of correct ways of doing the same thing such as this. It is your choice really.
Cheers.
DWORD FA = GetFileAttributes(path);
if (FA != (DWORD) -1) {
// The path exists
if (FA & FILE_ATTRIBUTE_DIRECTORY) {
// It's a directory
}
}
But the truth is that there are a number of correct ways of doing the same thing such as this. It is your choice really.
Cheers.
Best, fastest, most reliable way is to use stat. run "man 2 stat" to see the man page.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
....
struct stat mystat;
int res;
res = stat(filename, &mystat);
if (res != 0) {
printf("can't stat %s: %s\n", filename, strerror(errno));
} else if (S_ISDIR(mystat.st_mode)) { // or use mystat.st_mode & 0x4000
printf("Yep, it's a directory\n");
} else {
printf("It exists, but it's not a directory\n");
}
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
....
struct stat mystat;
int res;
res = stat(filename, &mystat);
if (res != 0) {
printf("can't stat %s: %s\n", filename, strerror(errno));
} else if (S_ISDIR(mystat.st_mode)) { // or use mystat.st_mode & 0x4000
printf("Yep, it's a directory\n");
} else {
printf("It exists, but it's not a directory\n");
}
"stat"
http://www.hmug.org/man/2/stat.html
if it returns the error "ENOENT" that means the directory doestnt exist..
opendir sounds more descriptive that u r checking on a directory.. stat works for any file/dir
akshay