0

I do know how to read all the files from the current directory by opening directory "./" and then using readdir. But, how do I list only .txt files or any other specific extension?

  DIR *p;
  struct dirent *pp;     
  p = opendir ("./");

  if (p != NULL)
  {
    while ((pp = readdir (p))!=NULL)
      puts (pp->d_name);

    (void) closedir (pp);
  }
Adrian McCarthy
  • 45,555
  • 16
  • 123
  • 175
jimo
  • 430
  • 2
  • 7
  • 19
  • 5
    Loop through the files as you currently do and process only those whose name finishes with the specific extension you chose ? – Chnossos May 13 '15 at 13:42
  • 1
    Use a `for` loop in conjunction with `sscanf`. You could do something like count the number of '.' characters in the file name, then if everything after the last one read "txt", print the whole file name. – Gophyr May 13 '15 at 13:44
  • 2
    i think you are looking for http://linux.die.net/man/3/glob – mch May 13 '15 at 13:49
  • 2
    ***[Look Here](http://stackoverflow.com/q/8149569/645128)*** – ryyker May 13 '15 at 13:50
  • possible duplicate of [How to list files in a directory in a C program?](http://stackoverflow.com/questions/4204666/how-to-list-files-in-a-directory-in-a-c-program) – LPs May 13 '15 at 13:53
  • @LPs: not of that particular question, the OP already got that far. – Jongware May 13 '15 at 15:41

1 Answers1

2

Just check the filename before you print it.

  DIR *p;
  struct dirent *pp;     
  p = opendir ("./");

  if (p != NULL)
  {
    while ((pp = readdir (p))!=NULL) {
      int length = strlen(pp->d_name);
      if (strncmp(pp->d_name + length - 4, ".txt", 4) == 0) {
          puts (pp->d_name);
      }
    }

    (void) closedir (p);
  }

Incidentally you were also calling closedir() on your dirent (pp) rather than your DIR * (p).

Moldova
  • 1,641
  • 10
  • 13
  • Isn't it more advisable to use a case indifferent compare? Or is that too OS dependent? (On Windows, `".txt" == ".TXT"` but my own Mac has two modes for this -- and I can never recall which one is for what.) – Jongware May 13 '15 at 15:43
  • @Jongware Indeed it is. – fuz May 19 '15 at 11:50