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

Ale*_*lex 2 c++ directory file-io file-extension

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

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

if (file_extension == ".foo")
    num_files++;
for (int i = 0; i < num_files; i++)
    // do something
Run Code Online (Sandbox Code Playgroud)

显然,这个程序要复杂得多,但是这应该让你对我正在尝试做的事情有了一般的了解.

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

谢谢!

Ram*_* B. 6

这种功能是特定于操作系统的,因此没有标准的,可移植的方法.

但是,使用Boost的文件系统库,您可以以可移植的方式执行此操作,以及更多与文件系统相关的操作.


pax*_*blo 5

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();
}
Run Code Online (Sandbox Code Playgroud)

如上所述,您将用于遍历目录的实际功能是特定于操作系统的.

对于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);
}
Run Code Online (Sandbox Code Playgroud)