Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get only txt files from directory in c?

I would like to get names of only *.txt files in given directory, sth like this:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>

int main(int argc, char **argv)
{
    char *dirFilename = "dir";

    DIR *directory = NULL;

    directory = opendir (dirFilename);
    if(directory == NULL)
        return -1;

    struct dirent *ent;

     while ((ent = readdir (directory)) != NULL)
     {
         if(ent->d_name.extension == "txt")
            printf ("%s\n", ent->d_name);
     }

    if(closedir(directory) < 0)
        return -1;

    return 0;
}

How can I do this in pure unixs c?

like image 441
Katie Avatar asked Nov 30 '22 02:11

Katie


2 Answers

Firstly, Unix has no notion of file extensions, so there's no extension member on struct dirent. Second, you can't compare strings with ==. You can use something like

bool has_txt_extension(char const *name)
{
    size_t len = strlen(name);
    return len > 4 && strcmp(name + len - 4, ".txt") == 0;
}

The > 4 part ensures that the filename .txt is not matched.

(Obtain bool from <stdbool.h>.)

like image 123
Fred Foo Avatar answered Dec 05 '22 02:12

Fred Foo


You can use the glob() function call for that. More info using your favourite search engine, Linux man pages, or here.

#include <glob.h>
#include <stdio.h>

int main(int argc, char **argv) {
  const char *pattern = "./*.txt";
  glob_t pglob; 

  glob(pattern, GLOB_ERR, NULL, &pglob);      

  printf("Found %d matches\n", pglob.gl_pathc);
  printf("First match: %s\n", pglob.gl_pathv[0]);

  globfree(&pglob);


  return 0;
}
like image 36
Bart Friederichs Avatar answered Dec 05 '22 02:12

Bart Friederichs