Listing only regular files, problem with stat
I want to list regular files in a directory. However, stat
fails for every file.
DIR* dp = NULL;
struct dirent* entry = NULL;
dp = opendir(directory);
if (!dp) { log_err("Could not open directory"); return -1; }
while (entry = readdir(dp))
{
struct stat s;
char path[1024]; path[0] = 0;
strcat(path, directory);
strcat(path, entry->d_name);
int status = 0;
if (status = stat(path, &s))
{
if (S_ISREG(s.st_mode))
{
printf("%s\n", entry->d_name);
}
}
else
{
fprintf(stderr, "Can't stat: %s\n", strerror(errno));
}
}
closedir(dp);
The output is
Can't stat: Resource temporarily unavailable
Can't stat: Resource temporarily unavailable
Can't stat: Resource temporarily unavailable
(... many times)
errno
is set to E_AGAIN
(11).
Now, if I printf the resulting path
, they are indeed valid file and directory names. The directory is readable, the user I run with does have the rights to do so (it's the directory where I write the program in).
What is causing this problem, and how can I do this correctly?
stat
and many other system calls return 0
on success and -1
on failure. You are incorrectly testing the return value of stat
.
Your code should be:
if (!stat(path, &s))
{
if (S_ISREG(s.st_mode))
{
printf("%s\n", entry->d_name);
}
}
else
{
fprintf(stderr, "Can't stat: %s\n", strerror(errno));
}
You are probably missing a delimitier.
strcat(path, directory);
strcat(path, "/"); //this is missing
strcat(path, entry->d_name);
Don't forget to account for the extra '/' when allocating your string.
精彩评论