C++遍历文件夹
1 struct _finddata_t 2 { 3 unsigned attrib; //文件属性 4 time_t time_create; //文件创建时间 5 time_t time_access; //文件上一次访问时间 6 time_t time_write; //文件上一次修改时间 7 _fsize_t size; //文件字节数 8 char name[_MAX_FNAME]; //文件名 9 };
文件属性是无符号整数,取值为相应的宏:_A_ARCH(存档),_A_SUBDIR(文件夹),_A_HIDDEN(隐藏),_A_SYSTEM(系统),_A_NORMAL(正常),_A_RDONLY(只读)。
以下函数,我们可以将文件信息存储到这个结构体中:
1 //按FileName命名规则匹配当前目录第一个文件 2 _findfirst(_In_ const char * FileName, _Out_ struct _finddata64i32_t * _FindData); 3 //按FileName命名规则匹配当前目录下一个文件 4 _findnext(_In_ intptr_t _FindHandle, _Out_ struct _finddata64i32_t * _FindData); 5 //关闭_findfirst返回的文件句柄 6 _findclose(_In_ intptr_t _FindHandle);
_findfirst 函数返回的是匹配到文件的句柄,数据类型为long。
1 #include "io.h" 2 void dfs_folder(std::string pathname, std::ofstream &fout) 3 { 4 _finddata_t file; 5 6 std::string findpath = pathname + "\\*"; 7 8 long handle = _findfirst(findpath.c_str(), &file); 9 10 if(handle == -1L) 11 { 12 std::cerr << "can not match the folder path" <<std::endl; 13 std::cout << pathname << std::endl; 14 system("PAUSE"); 15 exit(-1); 16 } 17 18 do 19 { 20 if(file.attrib & _A_SUBDIR) 21 { 22 if( (strcmp(file.name, ".") != 0) && (strcmp(file.name, "..") != 0) ) 23 { 24 std::string newpath = pathname + "\\" + file.name; 25 dfs_folder(newpath, fout); 26 } 27 } 28 else 29 { 30 //std::cout << pathname + "\\" + file.name << std::endl; 31 fout << file.name << std::endl; 32 } 33 }while( _findnext(handle, &file) == 0 ); 34 35 _findclose(handle); 36 }