get specific format files in directory

This is C code to get all the file names in the directory. Here I want to only specific format files. Format example I would like to list out only .txt files . How can I change this code to list out only specific formats ?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <sys/types.h>
#include <dirent.h>

#include <stdio.h>

int main(int argc, char *argv[])
{
  struct dirent *de=NULL;
  DIR *d=NULL;

  if(argc != 2)
  {
    fprintf(stderr,"Usage: %s dirname\n",argv[0]);
    return(1);
  }

  d=opendir(argv[1]);
  if(d == NULL)
  {
    perror("Couldn't open directory");
    return(2);
  }

  // Loop while not NULL
  while(de = readdir(d))
    printf("%s\n",de->d_name);

  closedir(d);
  return(0);
}
you would just have to parse de->d_name
when you hit a . you know everything already parsed is the file name and everything not yet parsed is the extension. i would suggest using strtok() to tokenize the name but you also have to be careful because in nix systems you dont have to have an extension for it to be a valid file.
Last edited on
Agreed, you need to parse d_name. In your case, you need to match the end to .txt:
1
2
3
4
5
if (strlen(e->d_name) >= 4 &&
    strcmp(d_name[ strlen(e->d_name) - 4 ], ".txt") == 0)
{
    printf("%s\n", e->d_name);
}


I'm not in agreement about the use of strtok(), however.

In general, you'll need a regular expression parser. Check out man 3 glob for the built in one that native utilities like the shells use.
Last edited on
Topic archived. No new replies allowed.