参考:https://blog.csdn.net/HolaMirai/article/details/53307518
实现功能
1、读取指定文件夹下的全部文件名列表,保存在一个vector中
2、根据文件名依次逐行读取文件中的内容,以追加的方式保存在一个新的文件中,完成多个单文件的内容集合
代码实现
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <io.h>
using namespace std;
/************************************************************************/
/* 获取文件夹下所有文件名
输入:
path : 文件夹路径
exd : 所要获取的文件名后缀,如jpg、png等;如果希望获取所有
文件名, exd = ""
输出:
files : 获取的文件名列表
*/
/************************************************************************/
void getFilesList(string path, string exd, vector<string>& files)
{
//文件句柄
long hFile = 0;
//文件信息
struct _finddata_t fileinfo;
string pathName, exdName;
if (0 != strcmp(exd.c_str(), ""))
{
exdName = "\*." + exd;
}
else
{
exdName = "\*";
}
if ((hFile = _findfirst(pathName.assign(path).append(exdName).c_str(), &fileinfo)) != -1)
{
do
{
if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
//files.push_back(pathName.assign(path).append("\").append(fileinfo.name)); // 要得到绝对目录使用该语句
//如果使用
files.push_back(fileinfo.name); // 只要得到文件名字使用该语句
} while (_findnext(hFile, &fileinfo) == 0);
_findclose(hFile);
}
}
int main()
{
//获取该路径下的所有txt文件名称,存入数组files中
vector<string> files;
getFilesList("allFiles/", "txt", files);
/*已获取到文件名列表,保存在files中*/
string prefix = "allFiles/";//文件路径前缀
ofstream out("all.txt", ofstream::app);//以追加形式写入
if (!out) {
cerr << "无法打开输出文件" << endl;
return -1;
}
for (auto file : files) {//遍历每个文件名,读取其内容,依次追加到all.txt文件中
string str;
string fileName = prefix + file;//文件路径前缀+文件名称
ifstream in(fileName);
if (in)//若文件打开成功
{
while (getline(in, str))//逐行获取in句柄绑定的文件内容
{
out << str << endl;
}
}else {//若文件打开失败
cerr << "无法打开输入文件" << endl;
return -1;
}
}
return 0;
}