计算目录和子目录C ++中具有特定扩展名的文件

时间:2016-12-24 02:44:19

标签: c++ recursion directory subdirectory

例如:.txt

C:\Duck\aa.txt
C:\Duck\Dog\Pig\cc.txt
C:\Duck\Dog\kk.txt
C:\Duck\Cat\zz.txt
C:\xx.txt

返回5

3 个答案:

答案 0 :(得分:0)

您必须使用opendir()readdir()

示例:

DIR *dir = opendir("."); // current dir
if (dir == NULL) {
  perror("opendir: .");
  return 1;
}

struct dirent *dirent;
while ((dirent = readdir(dir)) != NULL) {
  printf("%s\n", dirent->d_name);
}

closedir(dir);

答案 1 :(得分:-1)

请试试。

#include <sys/types.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
int count = 0;
void listdir(const char *name, int level)
{

    DIR *dir;
    struct dirent *entry;
    if (!(dir = opendir(name)))
        return;
    if (!(entry = readdir(dir)))
        return;

    do {
        if (entry->d_type == DT_DIR) {
            char path[1024];
            int len = snprintf(path, sizeof(path)-1, "%s/%s", name, entry->d_name);
            path[len] = 0;
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
                continue;
            listdir(path, level + 1);
        }
        else {
            const char *ext = strrchr(entry->d_name,'.');
            if((!ext) || (ext == entry->d_name))
                ;
            else {
                if(strcmp(ext, ".txt") == 0) {
                    printf("%*s- %s\n", level * 2, "", entry->d_name);
                    count++;
                }
            }

        }
    } while (entry = readdir(dir));
    closedir(dir);

}

int main(void)
{
    listdir(".", 0);
    printf("There are %d .txt files in this directory and its subdirectories\n", count);
    return 0;
}

测试

./a.out
- hi.txt
- payfile.txt
- csis.txt
- CMakeCache.txt
- text.txt
- sorted.txt
- CMakeLists.txt
- ddd.txt
- duom.txt
- output.txt
      - mmap_datafile.txt
      - file_datafile.txt
  - CMakeLists.txt
    - link.txt
  - TargetDirectories.txt
There are 15 .txt files in this directory and its subdirectories

答案 2 :(得分:-1)

谢谢大家的答案,你尝试过的代码:

WIN32_FIND_DATA fdata;
int counter = 0;
if (HANDLE first = FindFirstFile(L"C:\\duck\\*.txt", &fdata))
{
    counter++;
    do 
    {
        counter++;
    } while (FindNextFile(first, &fdata));
}

但正如你所看到的那样,我没有得到我想要的结果,包括子目录。 感谢&#34; Dac Saunders&#34;对所有其他人来说,它帮助了很多。