0

I have a problem, in that I need to get a list of the files in a Directory. Using this previous StackOverflow question as a base, I've currently got this code:

void get_files(int maxfiles) {
    int count = 0;
    DIR *dir;
    struct dirent *ent;
    dir = opendir(DIRECTORY);
    if (dir != NULL) {

        /* get all the files and directories within directory */
        while ((ent = readdir(dir)) != NULL) {
            if (count++ > maxfiles) break;

            printf("%s\n", ent->d_name);
        }
        closedir(dir);
    } else {
        /* could not open directory */
        printf("ERROR: Could not open directory");
        exit(EXIT_FAILURE);
    }
}

Now it works almost exactly how I want it too, but the problem is that its also listing directories in with he files, and I only want file entries. Is there a easy modification I can make to do this?

Community
  • 1
  • 1
Ash
  • 24,276
  • 34
  • 107
  • 152

3 Answers3

3

You can filter directories using code similar to this one

Community
  • 1
  • 1
Dmitriy
  • 2,742
  • 1
  • 17
  • 15
2

POSIX defines fstat which can be used for the purpose of checking whether a file is a directory. It also has a macro to simplify the check.
http://linux.die.net/man/2/fstat
Note that for Windows you may have to use windows API here.

buddhabrot
  • 1,558
  • 9
  • 14
0

If your struct dirent contains the nonstandard-but-widely-available d_type member, you can use this to filter out directories. Worth having an option to use it and only falling back to stat on systems that don't, since using d_type rather than stat will possibly make your directory listing tens or hundreds of times faster.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711