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

来源:互联网 发布:淘宝封店支付宝还能用 编辑:程序博客网 时间:2024/05/16 15:45
/*本代码实现遍历双层次层次的目录结构*/#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;}