废话不多说先上程序:
#include <stdio.h> #include <tchar.h> #include<io.h> #include<stdlib.h> #include<iostream> #include<string> using namespace std; int ayu = 0; int change_path(string path, stringnew_path){ int i = path.length(); new_path = "\\" + new_path + "*.*"; path.replace(i - 2, i, new_path); return 0; } int find_file( string a ) { string s1,s2; long Handle; s1.replace(NULL, NULL, a); struct _finddata_t FileInfo; cout << ayu << "\t" << endl; if ((Handle = _findfirst(a.c_str(), &FileInfo)) == -1L){ if (_A_SUBDIR & FileInfo.attrib){ if ((strcmp(FileInfo.name, ".") != 0) &&(strcmp(FileInfo.name, "..") != 0)){ printf("%s\n", FileInfo.name); s2.replace(NULL, NULL, FileInfo.name); change_path(s1, s2); ayu = ayu + 1; find_file(s1); } } } else{ printf("%s\n", FileInfo.name); while (_findnext(Handle, &FileInfo) == 0){ if (_A_SUBDIR & FileInfo.attrib){ if ((strcmp(FileInfo.name, ".") != 0) &&(strcmp(FileInfo.name, "..") != 0)){ printf("%s\n", FileInfo.name); s2.replace(NULL, NULL, FileInfo.name); change_path(s1, s2); ayu = ayu + 1; find_file(s1); } } printf("%s\n", FileInfo.name); } _findclose(Handle); } ayu -= 1; system("pause"); return 0; } int _tmain(int argc, _TCHAR* argv[]) { string s; cout << "please inupt path:"; cin >> s; find_file(s); return 0;
} 主要思路就是通过对find_file()的递归调用来达到遍历目录的目的(ayu变量是在检错的时候加上去的)
但是实际运行的时候出来这样的错误
运行结果
变量ayu显示程序在这两个文件上重复了上千次。
然而想了好久实在不知道是哪里错了orz
|