POSIX Count number of text files in the directory


Example

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <dirent.h>
#include <ctype.h>

int main(int argc, char **argv)
{
    const char *dname = (argc > 1 ? argv[1] : ".");
    DIR* pdir = opendir(dname);
    if(pdir == NULL) {
        perror("Can't open directory");
        return EXIT_FAILURE;
    }
    int textfiles=0;
    struct dirent* dent;
    while ((dent=readdir(pdir))!=NULL) {
        int d_name_len = strlen(dent->d_name);
        if (d_name_len > 4 &&
                strcmp(dent->d_name + (d_name_len - 4), ".txt") == 0) {
            textfiles++;
        }
    }
    printf("Number of text files: %i\n", textfiles);
    closedir(pdir);
    return 0;
}