深度搜索遍历文件夹
深度优先搜索遍历文件夹所有文件, 由于使用windows的函数, 必须要使用C语言;
注意字符集的问题,使用"#undef UNICODE", 屏蔽因字符集所产生的问题;
使用vector<string>存储所有文件名, 因为要递归使用, 所以需要设置为静态,返回shared_ptr的指针
代码如下:
/*************************************************
File: main.cpp
Copyright: C.L.Wang
Author: Caroline
Date: 2013-11-27
Description: 深度优先递归遍历目录中所有的文件
Email: morndragon@126.com
**************************************************/
#undef UNICODE
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <cstring>
#include <windows.h>
std::shared_ptr<std::vector<std::string> >
fileList(const std::string& folder_path)
{
static std::shared_ptr<std::vector<std::string> >
folder_files(new std::vector<std::string>); //返回指针, 需要迭代使用
WIN32_FIND_DATA FindData;
HANDLE hError;
int file_count(0);
std::string file_path(folder_path); //路径名
std::string full_file_path; //全路径名
file_path.append("/*.*");
hError = FindFirstFile(file_path.c_str(), &FindData);
if (hError == INVALID_HANDLE_VALUE) {
std::cout << "failed to search files." << std::endl;
return nullptr;
}
while(FindNextFile(hError, &FindData))
{
//过虑".", "..", "-q"
if(0 == strcmp(FindData.cFileName, ".") ||
0 == strcmp(FindData.cFileName, "..") ||
0 == strcmp(FindData.cFileName, "-q"))
{
continue;
}
//完整路径
full_file_path.append(folder_path);
full_file_path.append("/");
full_file_path.append(FindData.cFileName);
++file_count;
if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY){
//std::cout << file_count << " " << full_file_path << "<Dir>" << std::endl;
fileList(full_file_path);
}else{
folder_files->push_back(full_file_path);
//std::cout << file_count << " " << full_file_path << std::endl;
}
full_file_path.clear(); //清空目录
}
return folder_files;
}
int main(void)
{
std::shared_ptr<std::vector<std::string> > folder_files;
folder_files = fileList("E:/Picture/shoes3");
if (folder_files) {
for (size_t i=0; i != folder_files->size(); ++i) {
std::cout << i+1 << " : " << (*folder_files)[i] << std::endl;
}
}
return 0;
}
分享到:
相关推荐
Linux 刚刚开始学,挺实用的。Linux-C++-遍历指定文件夹路径下的文件列表并将路径写到txt文件。 如果没有积分,请私信我留下邮箱,我会尽快发过去
c++-深度优先遍历的递归实现版本
在window下,使用c++遍历文件夹及其子文件夹所有文件 并输出文件路径和文件内容。网上的资源大多都只是遍历文件夹,但是我需要打印出文件内容,所以自己弄了两天,这就是我的成果(*^__^*) ……
遍历文件夹并建成目录树__遍历文件夹并建成目录树-traverse file folders and create directory tree
C++遍历指定文件夹中的所有文件 遍历方法
Graph(邻接矩阵)-两种遍历。 (1)建立图的邻接矩阵; (2)对其进行深度优先及广度优先遍历。
数据结构 C++ 源码 深度优先遍历 实现树的深度优先遍历
遍历文件夹并建成目录树__遍历文件夹并建成目录树
c c++ c语言遍历文件夹 c语言读文件 c语言写文件 高效算法
数据结构实验--图的遍历,最短路线选择
在邻接矩阵的存储结构下,实现图的深度优先遍历和广度优先遍历。
如何遍历文件夹查找文件如何遍历文件夹查找文件
VC遍历文件夹并建成目录树.visual c++
c c++ c语言遍历文件夹 c语言读文件 c语言写文件
XXX大学数据结构课程设计,由个人完成,为大家提供参考。
C++遍历指定文件夹下的所有文
2---前序遍历(递归) 3---前序遍历(非递归) 4---中序遍历(递归) 5---中序遍历(非递归) 6---后序遍历(递归) 7---后序遍历(非递归) 8---求树高 9---求叶子总数 10---输出二叉树 11---交换左右子树 ...
使用IHTML族接口对已打开的IE窗口的表单进行枚举获取。 演示了IE窗口的获取和IHTML族接口的使用
实现二叉树遍历,要求采用两种遍历方式实现,其中层次遍历为必选,另一实现可选择层次、前序、后序、中序中的任意一种;作业中应明确指出自身所采用的遍历方式。
C/C++遍历文件夹感觉真是很不好用,建议还是使用C/C++做单任务处理,然后通过脚本语言实现遍历比较合理。 CBrowseDir.h #include #include #include #include #include #include <vector>