2

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

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

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

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

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

谢谢!

4

3 回答 3

6

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

但是,使用Boost 的 Filesystem 库,您可以做到这一点,并以可移植的方式执行更多与文件系统相关的操作。

于 2009-12-20T08:53:11.867 回答
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();
}

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

对于 UNIX,几乎可以肯定会使用opendirreaddirclosedir。这段代码是一个很好的起点:

#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);
}
于 2009-12-20T08:57:50.857 回答
1

首先,您要为什么操作系统编写代码?

  • 如果是 Windows,则在 MSDN 中查找FindFirstFile和。FindNextFile
  • 如果您正在寻找 POSIX 系统的代码,请man阅读opendirand readdiror readdir_r
  • 对于跨平台,我建议使用 Boost.Filesystem 库。
于 2009-12-20T08:53:18.387 回答