count number of files with a given extension in a directory - C++?

前端 未结 3 505
慢半拍i
慢半拍i 2021-01-15 04:35

Is it possible in c++ to count the number of files with a given extension in a directory?

I\'m writing a program where it would be nice to do something like this (ps

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-15 04:40

    There is nothing in the C or C++ standards themselves about directory handling but just about any OS worth its salt will have such a beast, one example being the findfirst/findnext functions or readdir.

    The way you would do it is a simple loop over those functions, checking the end of the strings returned for the extension you want.

    Something like:

    char *fspec = findfirst("/tmp");
    while (fspec != NULL) {
        int len = strlen (fspec);
        if (len >= 4) {
            if (strcmp (".foo", fspec + len - 4) == 0) {
                printf ("%s\n", fspec);
            }
        }
        fspec = findnext();
    }
    

    As stated, the actual functions you will use for traversing the directory are OS-specific.

    For UNIX, it would almost certainly be the use of opendir, readdir and closedir. This code is a good starting point for that:

    #include 
    
    int len;
    struct dirent *pDirent;
    DIR *pDir;
    
    pDir = opendir("/tmp");
    if (pDir != NULL) {
        while ((pDirent = readdir(pDir)) != NULL) {
            len = strlen (pDirent->d_name);
            if (len >= 4) {
                if (strcmp (".foo", &(pDirent->d_name[len - 4])) == 0) {
                    printf ("%s\n", pDirent->d_name);
                }
            }
        }
        closedir (pDir);
    }
    

提交回复
热议问题