Aaron Rennow
Aaron Rennow

Reputation: 95

How to check if a dir exists?

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.

Upvotes: 3

Views: 11959

Answers (4)

vicatcu
vicatcu

Reputation: 5837

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

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");
  }
  else closedir(dip);

Upvotes: 4

ghostdog74
ghostdog74

Reputation: 342273

struct stat st;
if(stat("/directory",&st) == 0) 
        printf(" /directory is present\n");

Upvotes: 6

Richard Pennington
Richard Pennington

Reputation: 19965

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

Upvotes: 0

Steven Schlansker
Steven Schlansker

Reputation: 38526

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.

Upvotes: 7

Related Questions