Search code examples
cstatopendirreaddir

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.


Solution

  • 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).