这两天一直在学习如何使用c++遍历文件夹、读取文件内容和写入文件。
话不多说,直接上代码
/*
* 文件功能:递归遍历文件夹,遍历文件夹及其子文件夹和文件.打印文件夹名称、文件名称和文件数目
*
*
* 参考:https://www.cnblogs.com/collectionne/p/6792301.html
* 句柄(handle):是Windows用来标志应用程序中建立的或是使用的唯一整数,Windows大量使用了句柄来标识对象。
* 原型声明:extern char *strcat(char *dest, const char *src);
* 函数功能:把src所指字符串添加到dest结尾处(覆盖dest结尾处的'\0')。
* 原型声明:char *strcpy(char* dest, const char *src);
* 函数功能:把从src地址开始且含有NULL结束符的字符串*复制到以dest开始的地址空间。
*/
#include "stdafx.h"
#include <iostream>
#include <cstring> // for strcpy_s(), strcat_s()
#include <io.h>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
void listFiles(const char * dir, std::vector<const std::string> &fileList);
int main()
{
std::vector<const std::string> fileList; //定义一个存放结果文件名称的链表
listFiles("D:/VS2017/VS2017 DATA/test/test1/mulu", fileList); // 这里输目录路径,绝对路径
for (int i = 0; i < fileList.size(); i++)
{
cout << fileList[i] << endl;
}
cout << "文件数目:" << fileList.size() << endl; // 打印文件数目
return 0;
}
/*----------------------------
* 功能 : 递归遍历文件夹,找到其中包含的所有文件
*----------------------------
* 函数 : listFiles
* 访问 : public
*
* 参数 : dir [in] 需遍历的文件夹目录
* 参数 : fileList [in] 以文件名称的形式存储遍历后的文件
*/
void listFiles(const char * dir, std::vector<const std::string> &fileList)
{
char dirNew[200];
strcpy_s(dirNew, dir);
strcat_s(dirNew, "\\*.*"); // 在目录后面加上"\\*.*"进行第一次搜索.
intptr_t handle;
_finddata_t findData; // _finddata_t是存储文件各种信息的结构体
handle = _findfirst(dirNew, &findData);
if (handle == -1) // 检查是否成功
return;
do
{
if (findData.attrib & _A_SUBDIR) // 目录
{
if (strcmp(findData.name, ".") == 0 || strcmp(findData.name, "..") == 0)
continue;
cout << findData.name << "\t<dir>\n"; // 打印文件夹的名称
//fileList.push_back(findData.name); // 打印文件夹的名称
// 在目录后面加上"\\"和搜索到的目录名进行下一次搜索
strcpy_s(dirNew, dir);
strcat_s(dirNew, "\\");
strcat_s(dirNew, findData.name);
listFiles(dirNew, fileList);
}
else // 文件
{
fileList.push_back(findData.name); // 打印文件的名称,并且后面可以打印文件的数目
}
} while (_findnext(handle, &findData) == 0);
_findclose(handle); // 关闭搜索句柄
}
测试输出结果如下:
如果要遍历文件夹的所有文件,并输出文件路径和文件内容,我上传了我的代码,欢迎浏览
点击打开链接 https://download.csdn.net/download/yaodaoji/10344109
打印信息如下:
可以再此基础上对文件进行 写入文件和读取文件。