废话不多说先上程序:
#include <stdio.h>#include <tchar.h>#include<io.h>#include<stdlib.h>#include *本站禁止HTML标签噢*#include *本站禁止HTML标签噢*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
樱花流逝 发表于 2015-8-28 21:43初学还没接触过win api
如果用win api 的话该怎么写?
没有必要,因为一部分标准库函数在底层实现就是调用了系统的API。
[查看全文]
你这个代码里有很多问题,比如 change_path 来改变下一个遍历的路径,但没有用引用传参,也就是说,你调用了 change_path 之后, s1 里面的值根本没变化(楼主可以自己写段小代码测试下),建议改为如下:
[mw_shl_code=cpp,true]int change_path(string & path, string new_path)[/mw_shl_code]
另外,在 change_path 里面,你想用 s2 的目录名加在 s1 后面,只加上了前面的斜杠,却没有“*.*”与 s2 之间的分隔,建议改为如下:
[mw_shl_code=cpp,true]new_path = "\\" + new_path + "\\*.*";[/mw_shl_code]
如果你要加上这个子目录名字,没必要调用 replace 还要计算 s1 的长度,直接用“+”连接两个string对象就行了:
[mw_shl_code=cpp,true]path += new_path;[/mw_shl_code]
另外,在你的 find_file 函数里,也有很明显的问题,你的 if 居然是在 _findfirst 返回 -1L 的时候(也就是找不到任何匹配项)去执行 if 里面的语句、进入子目录。
如果你给 _findfirst 传入的第一个参数是一个目录名,例如“C:\\XX\\YY”,只要这目录存在就能被 _findfirst 正常打开,而且它在FileInfo的name里写入的字符串会是“YY”,而不是“YY”下面的目录或文件名,更不会返回 -1L, 你的代码却还要在返回 -1L 的情况下进去挖掘子目录,这个问题是很明显的。
[查看全文]