赞
踩
遍历当前目录下的文件,不含多级目录
- /****************************************
- * 遍历当前目录下的文件夹和文件,默认是按字母顺序遍历
- ****************************************/
- #include<io.h>
- #include<iostream>
- using namespace std;
- bool FindAllFilesOnCurFolder(string path, int &file_num)
- {
- _finddata_t file_info;
- //可以定义后面的后缀为*.exe,*.txt等来查找特定后缀的文件,*.*是通配符,匹配所有类型,路径连接符最好是左斜杠/,可跨平台
- string current_path = path + "/*.*";
- int handle = _findfirst(current_path.c_str(), &file_info);
- //返回值为-1则查找失败
- if (-1 == handle)
- return false;
- do
- {
- string attribute;
- if (file_info.attrib == _A_SUBDIR) //是目录
- attribute = "dir";
- else
- attribute = "file";
-
- //获得的最后修改时间是time_t格式的长整型
- cout << file_info.name << ' ' << file_info.time_write << ' ' << file_info.size << ' ' << attribute << endl;
- file_num++;
-
- } while (!_findnext(handle, &file_info));
-
- //关闭文件句柄
- _findclose(handle);
- return true;
- }

多级目录遍历文件
- /*
- *深度优先递归遍历当前目录下的文件夹、文件及子文件夹和文件
- */
- #include<io.h>
- #include<iostream>
- using namespace std;
- void DfsListFolderFiles(string path)
- {
- _finddata_t file_info;
- string current_path = path + "/*.*";
- int handle = _findfirst(current_path.c_str(), &file_info);
- //返回值为-1则查找失败
- if (-1 == handle)
- {
- cout << "cannot match the path" << endl;
- return;
- }
-
- do
- {
- //目录
- if (file_info.attrib == _A_SUBDIR)
- {
- cout << file_info.name << endl;
- //.是当前目录,..是上层目录,须排除掉这两种情况
- if (strcmp(file_info.name, "..") != 0 && strcmp(file_info.name, ".") != 0)
- DfsListFolderFiles(path);
- }
- else
- {
- cout << file_info.name << endl;
- }
- } while (!_findnext(handle, &file_info));
- //关闭文件句柄
- _findclose(handle);
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。