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

计算目录-C+;中具有给定扩展名的文件数+;? < C++ >在目录中是否可以计算给定扩展名的文件数?,c++,file-io,directory,file-extension,C++,File Io,Directory,File Extension,我正在编写一个程序,在该程序中可以执行类似的操作(伪代码): if(文件扩展名=“.foo”) num_文件++; 对于(int i=0;i 这样做的方法是在这些函数上进行简单的循环,检查为所需扩展返回的字符串的结尾 比如: char *fspec = findfirst("/tmp"); while (fspec != NULL) { int len = strlen (fspec); if (len >= 4) { if (strcmp (".foo"

我正在编写一个程序,在该程序中可以执行类似的操作(伪代码):

if(文件扩展名=“.foo”)
num_文件++;
对于(int i=0;i
显然,这个程序要复杂得多,但这应该能让你大致了解我要做的事情

如果这不可能,就告诉我


谢谢

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


但是,使用您可以以可移植的方式完成此操作,以及更多与文件系统相关的操作。

首先,您编写操作系统的目的是什么

  • 如果是Windows,则在MSDN中查找
    FindFirstFile
    FindNextFile
  • 如果您正在查找POSIX系统的代码,请阅读
    man
    中的
    opendir
    readdir
    readdir\r
  • 对于跨平台,我建议使用Boost.Filesystem库

在目录处理中,C或C++标准本身没有任何东西,但是任何一个有价值的操作系统都会有这样的一个畜牲,一个例子是<代码> FIDENATION/FIXNET/<代码>函数或<代码> RADDIR< <代码> >

这样做的方法是在这些函数上进行简单的循环,检查为所需扩展返回的字符串的结尾

比如:

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,几乎可以肯定的是使用和。这段代码是一个很好的起点:

#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);
}
#包括
内伦;
结构方向*pDirect;
DIR*pDir;
pDir=opendir(“/tmp”);
如果(pDir!=NULL){
而((pDirent=readdir(pDir))!=NULL){
len=strlen(pDirent->d_name);
如果(len>=4){
如果(strcmp(“.foo”,&(pDirent->d_name[len-4]))==0){
printf(“%s\n”,pDirent->d_name);
}
}
}
closedir(pDir);
}

在上述两种情况下。“for(;;)循环不是更整洁吗?我想是品味或风格的问题,”马丁说。我倾向于将for循环用于简单的事情(主要是“for I=1到10”排序),而将while用于更复杂的循环。但不管是哪种情况,都与眼前的问题无关。
#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);
}