Linux下C/C++读取文件夹下所有文件数据到一个文件中

之前写的代码,现在一看里面多了很多没用的string和char *转换。如果有需要可以进行精简,主要是体现主体逻辑

实现思想就是先读到目录下所有的文件名,再打开文件读取内容,统一写到一个文件中

#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <vector>
#include <cstring>
using namespace std;

// function:从指定文件内读取数据并返回
std::string Get_data(char file_name[100]) {
    
    
	fflush(stdin);
	char line[500];
	FILE *fp;
	if ((fp=fopen(file_name, "r")) == NULL) {
    
    
		cout << "output fail to open" << endl;
		exit(-1);
	}
	char total_data[2048] = "";
	while (fgets(line, sizeof(line), fp) != NULL) {
    
    
		strcat(total_data, line);
	} 
	fclose(fp);
	string data(total_data);
	return data;
}

// function:获取路径下所有文件名,存在filenames中
void getFiles(string path, vector<string>& filenames)
{
    
    
	DIR *pDir;
    struct dirent* ptr;
    if(!(pDir = opendir(path.c_str()))){
    
    
        cout<<"Folder doesn't Exist!"<<endl;
        return;
    }
    while((ptr = readdir(pDir))!=0) {
    
    
        if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0){
    
    
            filenames.push_back(path + "/" + ptr->d_name);
    	}
    }
    closedir(pDir);
}


int main(int argc, char** argv)
{
    
    
	string filePath = "./all_topic_data";   // 待读取文件夹路径
	vector<string> files;
 
	//获取该路径下的所有文件
	getFiles(filePath, files);
 
	char str[30];
	int size = files.size();
	int nullSize = 0;
	for (int i = 0; i < size; i++)
	{
    
    
        string data = Get_data((char *)files[i].c_str());
        char *line;
	    FILE *fp;
	    if ((fp=fopen("all_data.json", "a")) == NULL) {
    
    
		    cout << "output fail to open" << endl;
		    exit(-1);
	    }
        line = (char *)data.c_str();
        fputs(line, fp);
	    fclose(fp);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/gls_nuaa/article/details/129889415