Why does stat fail using a name from readdir? [duplicate]
Classic readdir
mistake: pDirent->d_name
is the name of the directory entry, not a path to the file. It's "1"
, "4-5.c"
, etc. So your stat
calls are looking for a file with that name in the current directory, not under MyDirectory
.
Check the return value of stat
. You'll see that it's ENOENT
— except for .
and ..
, which exist in the current directory as well. When stat
fails, the content of the stat structure is undefined.
If you're calling opendir
in a directory other than .
, then to do pretty much anything useful with the returned names, you need to build a full path. Copy the path you passed to opendir
to a buffer with enough room for a slash and file name in addition, and copy each file name to that buffer. Proof-of-concept code (error checking omitted, etc.):
char *directory = "MyDirectory";
size_t directory_length = strlen(directory);
char *path = malloc(directory_length + 1 + NAME_MAX);
strcpy(path, directory);
path[directory_length] = '/';
while ((pDirent = readdir(pDir)) != NULL) {
strcpy(path + directory_length + 1, pDirent->d_name);
if (stat(path, &vStat) == -1) {
perror(path);
continue;
}
…
}