例如特定扩展名:.txt文件计数的文件与目录和子目录C++
C:\Duck\aa.txt
C:\Duck\Dog\Pig\cc.txt
C:\Duck\Dog\kk.txt
C:\Duck\Cat\zz.txt
C:\xx.txt
返回5
例如特定扩展名:.txt文件计数的文件与目录和子目录C++
C:\Duck\aa.txt
C:\Duck\Dog\Pig\cc.txt
C:\Duck\Dog\kk.txt
C:\Duck\Cat\zz.txt
C:\xx.txt
返回5
请您尝试一下。
#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
谢谢大家的回答,您曾试图代码:
WIN32_FIND_DATA fdata;
int counter = 0;
if (HANDLE first = FindFirstFile(L"C:\\duck\\*.txt", &fdata))
{
counter++;
do
{
counter++;
} while (FindNextFile(first, &fdata));
}
但你可以用同样的看,我没有得到结果我正在寻找,其中包括子目录。 感谢“Dac Saunders”和所有其他人,这对我们有很大的帮助。
请参加[旅游]。如果你自己回答你的问题。答案需要是一个解决方案。你的回答很糟糕,因为我不明白你的英文,你说[“我得到的最多的是我的答案中的代码。”](http://stackoverflow.com/questions/41309872/count-files-在特定的扩展名在目录和子目录C/41309928#comment69834928_41309872)显然这个代码是行不通的。如果你想添加代码,你可以试试[编辑](http://stackoverflow.com/posts/41309872/edit)你的问题,并删除这个答案。或者用你的最终解决方案来编辑这个答案。 – Stargateur
在寻求帮助时,最好提供已尝试的代码和遇到的错误。要求社区为你写代码是不客观的。 –
这个问题表明您无法自行找到解决方案,包括在发布之前无法通过Google或本网站进行基本搜索。在目前的状态下,它对未来的读者绝对没有价值,应该关闭。 –
我得到的最多的是我的答案中的代码。抱歉,以前没有显示我的代码,是的,我已经搜索过,但我找不到在count中的子目录中包含.txt的方法,但我已经在Dac Saunders的帮助下管理。谢谢你们。 – Tito