The canonical way of determining a file's type is to use the commented out code in this snippet:
// Return the number of files in dirName. Ignore directories and links.
#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int fCt = 0;
struct dirent *dir;
DIR *d;
d = opendir(argv[1]);
if (d == NULL) {
printf("%s was not opened!\n", argv[1]);
exit(0);
}
// Count all of the files.
while ((dir = readdir(d)) != NULL) {
// struct stat buf;
// stat(dir->d_name, &buf);
// if (S_ISREG(buf.st_mode)) { fCt++; }
if (dir->d_type == 8) { fCt++; }
}
return fCt;
}
The element buf.st_mode returns 41ED (hex), 16877 (decimal) for both directories and regular files. S_ISREG fails to find the right bit set for both types.
Note that the line:
if (dir->d_type == 8) { fCt++; }
returns an accurate file count.
Why did the commented out method fail?