c++读取文件夹及子文件夹数据

这里有两种情况:读取文件夹下所有嵌套的子文件夹里的所有文件  和 读取文件夹下的指定子文件夹(或所有子文件夹里指定的文件名)

《ps,里面和file文件有关的结构体类型和方法在 <io.h>中》

情况二:只读取特定文件

void Files::getFiles( string path, vector<string>& files )
{
    //文件句柄
    long   hFile   =   0;
    //文件信息
    struct _finddata_t fileinfo;
    string p;
    if((hFile = _findfirst(p.assign(path).append("\\*").c_str(),&fileinfo)) !=  -1)
        //assign用于拷贝、赋值操作,它们允许我们顺次地把一个string 对象的部分内容拷贝到另一个string 对象上。
        //搜索与指定的文件名称匹配的第一个实例,若成功则返回第一个实例的句柄,否则返回-1L
    {
        do
        {
            
            if((fileinfo.attrib &  _A_SUBDIR))
            {
                //如果是目录,迭代之
                //如果不是,加入列表
                //if(strcmp(fileinfo.name,".") != 0  &&  strcmp(fileinfo.name,"..") != 0)//若str1==str2,则返回零;
                //getFiles( p.assign(path).append("\\").append(fileinfo.name), files );
                files.push_back(p.assign(path).append("\\").append(fileinfo.name).append("\\0.jpg")); 
            }            
            
        }while(_findnext(hFile, &fileinfo)  == 0);
        _findclose(hFile);
    }
}

 

会出现读取\\.和\\..的情况,解决方法如下:

void Files::getFiles( string path, vector<string>& files )
{
    //文件句柄
    long   hFile   =   0;
    //文件信息
    struct _finddata_t fileinfo;
    string p;
    if((hFile = _findfirst(p.assign(path).append("\\*").c_str(),&fileinfo)) !=  -1)
        //assign用于拷贝、赋值操作,它们允许我们顺次地把一个string 对象的部分内容拷贝到另一个string 对象上。
        //搜索与指定的文件名称匹配的第一个实例,若成功则返回第一个实例的句柄,否则返回-1L
    {
        do
        {
            
            if((fileinfo.attrib &  _A_SUBDIR))
            {
                //如果是目录,迭代之
                //如果不是,加入列表
                if(strcmp(fileinfo.name,".") != 0  &&  strcmp(fileinfo.name,"..") != 0)//这一行不要注释掉就不会读出. 和..了,做了判断
                //getFiles( p.assign(path).append("\\").append(fileinfo.name), files );
                files.push_back(p.assign(path).append("\\").append(fileinfo.name).append("\\0.jpg")); 
            }            
            
        }while(_findnext(hFile, &fileinfo)  == 0);
        _findclose(hFile);
    }
}

 

情况一:所有都读

 

#include "stdafx.h"
#include <io.h>
#include
<vector> #include "Files.h" using namespace std; void Files::getFiles( string path, vector<string>& files ) { //文件句柄 long hFile = 0; //文件信息 struct _finddata_t fileinfo; string p; if((hFile = _findfirst(p.assign(path).append("\\*").c_str(),&fileinfo)) != -1) //assign用于拷贝、赋值操作 //搜索与指定的文件名称匹配的第一个实例,若成功则返回第一个实例的句柄,否则返回-1L { do { //如果是目录,迭代之 //如果不是,加入列表 if((fileinfo.attrib & _A_SUBDIR)) { if(strcmp(fileinfo.name,".") != 0 && strcmp(fileinfo.name,"..") != 0)//若str1==str2,则返回零; getFiles( p.assign(path).append("\\").append(fileinfo.name), files );
}
else
{ files.push_back(p.assign(path).append("\\").append(fileinfo.name));
} }
while(_findnext(hFile, &fileinfo) == 0); _findclose(hFile);
}
}


posted @ 2015-05-11 15:21  Daringoo  阅读(1190)  评论(0编辑  收藏  举报