您的位置:首页 > 编程语言 > C语言/C++

c++对文件进行操作之遍历双层文件结构

2017-10-31 17:56 369 查看
/*本代码实现遍历双层次层次的目录结构*/
#include<stdio.h>
#include<iostream>
#include<io.h>
#include<cstring>
using namespace std;
const char path[100]="F:/OCR/*";
int main()
{
struct _finddata_t fileinfo;
char rootname[100];
long handle;
handle=_findfirst(path,&fileinfo);
if(handle==-1)
{
cout<<"文件路径错误..."<<endl;
return 0;
}
else
{
do{
if((fileinfo.attrib & _A_SUBDIR) && (strcmp(fileinfo.name,".")!=0) && (strcmp(fileinfo.name,"..")!=0) ) //用来判断一个文件是不是文件夹
{
int num=0;
long subhandle;//子文件夹的句柄
char subpath[100];//子文件夹的路径
strcpy(subpath,path);  subpath[strlen(path)-1]='\0'; //把path中的*去掉
strcat(subpath,fileinfo.name); strcat(subpath,"/*"); //生成新的子路径
struct _finddata_t subinfo;//子文件夹下用来遍历的结构体
subhandle=_findfirst(subpath,&subinfo);
if(subhandle==-1)
{
cout<<"子文件"<<fileinfo.name<<"打开失败"<<endl;
}else
{
do{
num++;
cout<<subinfo.name<<endl;
}while(_findnext(subhandle,&subinfo)==0);
_findclose(subhandle);
cout<<"如上所示文件"<<fileinfo.name<<"共有"<<num-2<<"个文件"<<endl<<endl;/*因为我在
遍历子文件夹的时候没有去判断 .和..这两种特殊文件,原谅我有点偷懒了*/
}
}
else
{
if(!fileinfo.attrib & _A_SUBDIR)
cout<<fileinfo.name<<endl;
}
}while(_findnext(handle,&fileinfo)==0);
_findclose(handle);
}
return 0;
}






                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: