I have a short program to output a directory's files. If I open the current directory with opendir("."), it works fine. But if I specify a path, it will list the filenames correctly, but the attributes are wrong. The mtime is wrong, the size is wrong, and the directory flag is wrong (probably others as well).
I added chdir() as a fluke and it works. But I'm not understanding why chdir() is necessary. Shouldn't opendir() return the data for that directory?
(I've taken this code from a book which, presumably, was tested and worked without chdir().)
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <time.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
int main(void) {
DIR *folder;
struct dirent *file;
struct stat filestat;
char s[6];
char *dir = "/home/mike/python";
folder = opendir(dir);
chdir(dir);
if (folder == NULL) {
puts("Unable to read directory");
exit(1);
}
while ((file=readdir(folder)) != NULL) {
stat(file->d_name, &filestat);
sprintf(s, "%5ld", filestat.st_size);
printf("%-14s %s %s",
file->d_name,
S_ISDIR(filestat.st_mode) ? "<DIR>" : s,
ctime(&filestat.st_mtime));
}
closedir(folder);
return(0);
}