Jordan
Jordan

Reputation: 2140

C - open and read directory, then determine file type

Alright, so I am having some issues. Here is my code (opendir() called before this):

while( (dp = readdir(dfd)) != NULL ) {
        if( strcmp(dp->d_name, ".") == 0 ||  strcmp(dp->d_name, "..") == 0)
            continue;

        lstat(dp->d_name, &stbuf);

        printf("%s: ", dp->d_name);

        if( S_ISDIR(stbuf.st_mode) )
            puts("Directory");
        else if ( S_ISREG(stbuf.st_mode) )
            puts("File");
        else if ( S_ISCHR(stbuf.st_mode) )
            puts("Character Device");
        else if ( S_ISBLK(stbuf.st_mode) )
            puts("Block Device");
        else if ( S_ISFIFO(stbuf.st_mode) )
            puts("Fifo");
        else if ( S_ISLNK(stbuf.st_mode) )
            puts("Link");
        else
            puts("Socket");
    }
    return;
}

I am reading through a directory and determining what the file type's are inside. The only problem is that this will always print "Directory" and I believe it has something to do with the call to lstat. I'm not exactly sure how to change it appropriately.

Upvotes: 1

Views: 6953

Answers (2)

unwind
unwind

Reputation: 399713

I can see two obvious causes for concern:

  1. You're not building the proper path. Unless you're in the directory (i.e. you did opendir(".")), you are passing the wrong path to lstat(). You need to concatenate the name of the directory with the name of each file. Opening the directory does not imply making it the current directory.
  2. You're not checking that lstat() succeeds, before inspecting its returned value.

Upvotes: 3

cnicutar
cnicutar

Reputation: 182619

lstat(dp->d_name, &stbuf);

Thing is dp->d_name contains only the name of the file, not the full path. So it probably fails, but you can't notice since you don't test its return value.

You need to prepend the path of the directory (i.e., what you passed to opendir).

Upvotes: 4

Related Questions