Click to See Complete Forum and Search --> : a directory:if it's there use it if not create it


bsamuels
10-08-2003, 09:05 PM
How would I check an argument as to whether it is a directory or not and if it exists, write to it and if not create it. I know about stat() and the necessary masks, but can't seem to figure the logic. If I attempt a opendir() I will generate an error if not there, and likewise if I try to stat the file and check it's type I will generate an error ...right??

bwkaz
10-08-2003, 09:28 PM
This assumes your passed-in argument is in the character array pointed to by the variable fname, and that you have a struct stat variable named info:

result = stat(fname, &info);

if(result == 0) {
/* then stat succeeded, so fname exists. */

if(S_ISDIR(info.st_mode)) {
/* put stuff here to be executed if fname is a directory. */
}
else {
/* fname points to an already-existing file of some
other type; you'll probably want to flag an error
and exit. */
}
}
else {
/* stat failed, so fname does not exist. Create the directory here. */
} The important part is the S_ISDIR() "function" (it's not actually a function, it's a preprocessor thingy, but it acts mostly like a function anyway).