1

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.

1
  • 2
    You need to prepend the path to the filename; lstat() does not know which directory the file is in. Also check the return value from lstat() Commented Jul 2, 2012 at 16:09

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.