views:

266

answers:

4

Hey guys, I'm relatively new to C, so forgive me if this is a stupid question, but how would I go about checking if a FILE is a directory? I have

if (file == NULL) {  
    fprintf(stderr, "%s: No such file\n", argv[1]);  
    return 1;  
} 

and that checks if the node exists at all, but I want to know if it's a dir or a file. I've done some googling, and I can't find an answer :\

Thanks,

-Aaron

+1  A: 

use opendir to try and open it as a directory. If that returns a null pointer it's clearly not a directory :)

Look here for example code.

Here's a snippet for your question:

  #include <stdio.h>
  #include <dirent.h>

   ...

  DIR  *dip;
  if ((dip = opendir(argv[1])) == NULL)
  {         
     printf("not a directory");
  }
vicatcu
+4  A: 

Filenames themselves don't carry any information about whether they exist or not or whether they are a directory with them - someone could change it out from under you. What you want to do is run a library call, namely stat(2), which reports back if the file exists or not and what it is. From the man page,

[ENOENT]           The named file does not exist.

So there's an error code which reports (in errno) that the file does not exist. If it does exist, you may wish to check that it is actually a directory and not a regular file. You do this by checking st_mode in the struct returned:

The status information word st_mode has the following bits:
...
#define        S_IFDIR  0040000  /* directory */

Check the manpage for further information.

Steven Schlansker
With your answer in mind, I discovered the S_ISDIR "macro" in the linux man page (notably not the OS X man page I'd been checking, though it works on both) that utilizes st_mode. I don't know if that's what you meant or not, but it works, so it's fine by me ;)
Aaron Lynch
A: 

If you're using *nix, stat().

Richard Pennington
+2  A: 
struct stat st;
if(stat("/directory",&st) == 0) 
        printf(" /directory is present\n");
ghostdog74