Reputation: 2140
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
Reputation: 399713
I can see two obvious causes for concern:
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.lstat()
succeeds, before inspecting its returned value.Upvotes: 3
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