在C++中,是否有可能统计目录中具有特定扩展名的文件数量?
我正在编写一个程序,希望能够像下面这样实现(伪代码):
if (file_extension == ".foo")
num_files++;
for (int i = 0; i < num_files; i++)
// do something
显然,这个程序要复杂得多,但这应该能让你大概了解我要做什么。 如果不可能,请告诉我。 谢谢!
在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、readdir 和 closedir 函数。以下代码是一个很好的起点:
#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);
}
首先,你要为哪个操作系统编写代码?
FindFirstFile
和 FindNextFile
。man
中的 opendir
和 readdir
或 readdir_r
。