递归遍历指定目录下的子目录和文件
/* 功能:演示了利用C语言递归遍历指定目录下的子目录和文件! 说明:经修改也可以搜索文件名符合特定格式的文件,如修改“\\*.*”为“\\*.log” */ #include <iostream> #include <string> #include <io.h> using namespace std; void filesearch(string path, int layer) { struct _finddata_t filefind; string curr = path + "\\*.*"; // 修改此处改变搜索条件 int done = 0, i, handle; if((handle = _findfirst(curr.c_str(), &filefind)) != -1) //c_str() 为兼容C,作用是将C++::string转为char { while(!(done = _findnext(handle, &filefind))) { if(strcmp(filefind.name, "..") == 0) continue; for(i = 0;i <layer; i++) printf("\t"); if((_A_SUBDIR == filefind.attrib)) // 是目录 { printf("[Dir]:\t%s\n", filefind.name); curr = path + "\\" + filefind.name; filesearch(curr, layer+1); // 递归遍历子目录 } else { printf("[File]:\t%s\n", filefind.name); } } _findclose(handle); } } int main() { string path("E:\\Program\\Proc"); filesearch(path, 0); return 0; }