【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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章