【C++】获取指定文件夹下的文件名列表,读取多个子文件追加写入一个新的文件

参考: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;
}

原文链接: https://www.cnblogs.com/dindin1995/p/13059109.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    【C++】获取指定文件夹下的文件名列表,读取多个子文件追加写入一个新的文件

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/343564

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午2:10
下一篇 2023年3月2日 上午2:10

相关推荐