gpt4 book ai didi

c++ - 计算目录中具有给定扩展名的文件数 - C++?

转载 作者:太空狗 更新时间:2023-10-29 23:34:40 25 4
gpt4 key购买 nike

在c++中是否可以计算目录中具有给定扩展名的文件的数量?

我正在编写一个程序,做这样的事情会很好(伪代码):

if (file_extension == ".foo")
num_files++;
for (int i = 0; i < num_files; i++)
// do something

显然,这个程序要复杂得多,但这应该让您大致了解我正在尝试做的事情。

如果这不可能,请告诉我。

谢谢!

最佳答案

C 或 C++ 标准本身没有关于目录处理的任何内容,但几乎任何称职的操作系统都会有这样的野兽,一个例子是 findfirst/findnext 函数或 readdir

您的做法是对这些函数进行简单的循环,检查为您想要的扩展返回的字符串的末尾。

类似于:

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();
}

如前所述,您将用于遍历目录的实际函数是特定于操作系统的。

对于 UNIX,几乎肯定会使用 opendir , readdirclosedir .这段代码是一个很好的起点:

#include <dirent.h>

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);
}

关于c++ - 计算目录中具有给定扩展名的文件数 - C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1935274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com