Ok...
This code (from your example) works fine. If I give it a filename it reports it as not a directory, and a directory is reported as a directory:
Code:
int main() {
int a;
char *filename = "directory/file.txt";
//char *filename = "directory/subdirectory";
struct stat buf;
stat(filename, &buf);
if (S_ISDIR(buf.st_mode)) {
printf("%-20s -- is a directory\n", filename);
} else {
printf("%-20s -- is not a directory\n", filename);
}
return 0;
}
However - when I try to combine this with the directory listing code I've been playing with, it doesn't work. This code lists the contents of a directory:
Code:
DIR *dp;
struct dirent *ep;
dp = opendir("./directory");
if (dp != NULL) {
while (ep = readdir(dp)) {
if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) {
continue;
}
//printf("%s,", ep->d_name);
struct stat buf;
stat(ep->d_name, &buf);
if (S_ISDIR(buf.st_mode)) {
printf("%-20s -- is a directory\n", ep->d_name);
}
else {
printf("%-20s -- is not a directory\n", ep->d_name);
}
}
(void)closedir(dp);
} else {
perror("Couldn't open the directory\n");
}
All entries are reported as "-- is not a directory". At first I thought it was related to some buffering and where I created the struct, and that the first entry (a file) would be "stuck" and not change. However, I'm not sure.
The contents of the directory:
anotherfile.exe
anothersubfolder
file
file.txt
subdirectory
yetanotherfile.bat
The above code lists this:
Code:
subdirectory -- is not a directory
anothersubfolder -- is not a directory
file.txt -- is not a directory
.file -- is not a directory
anotherfile.exe -- is not a directory
file -- is not a directory
yetanotherfile.bat -- is not a directory
If I place a break at the end of the while-loop, the only entry listed is
Code:
subdirectory -- is not a directory
If I remove the break, the first new entry is
Code:
subdirectory -- is a directory
anothersubfolder -- is a directory
file.txt -- is a directory
.file -- is a directory
anotherfile.exe -- is a directory
file -- is a directory
yetanotherfile.bat -- is a directory
But only for one run. The next run again reports all entries as not directories.
.