计数目录中给定扩展名的文件数 - C ++? [英] count number of files with a given extension in a directory - C++?

查看:168
本文介绍了计数目录中给定扩展名的文件数 - C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在编写一个程序,在那里做一个很好的工作这样的(伪代码):

  if(file_extension ==.foo)
num_files ++; (int i = 0; i< num_files; i ++)
//做某事

显然,这个程序要复杂得多,但是这应该是我想要做的一般的想法。



如果不是可能的,只是告诉我。



谢谢!

解决方案

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\\\
,fspec);
}
}
fspec = findnext();
}

如上所述,您将用于遍历目录的实际功能是OS-具体。



对于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\\\
,pDirent-> d_name);
}
}
}
closedir(pDir);
}


Is it possible in c++ to count the number of files with a given extension in a directory?

I'm writing a program where it would be nice to do something like this (pseudo-code):

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

Obviously, this program is much more complex, but this should give you the general idea of what I'm trying to do.

If this is not possible, just tell me.

Thanks!

解决方案

There is nothing in the C or C++ standards themselves about directory handling but just about any OS worth its salt will have such a beast, one example being the findfirst/findnext functions or readdir.

The way you would do it is a simple loop over those functions, checking the end of the strings returned for the extension you want.

Something like:

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

As stated, the actual functions you will use for traversing the directory are OS-specific.

For UNIX, it would almost certainly be the use of opendir, readdir and closedir. This code is a good starting point for that:

#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 ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆