1

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?

Boffin
  • 161
  • 8
  • You did not include the 3 header files that the stat documentation requires. – stark Jun 01 '19 at 20:28
  • `d = opendir(argv[1]); if (d == NULL) { perror(argv[1]);exit(EXIT_FAILURE); }` Because error message should be informative and written to stderr, and programs which exit when encountering an error should not return a value indicating that they were successful. – William Pursell Jun 03 '19 at 23:00

0 Answers0