之前写的代码,现在一看里面多了很多没用的string和char *转换。如果有需要可以进行精简,主要是体现主体逻辑
实现思想就是先读到目录下所有的文件名,再打开文件读取内容,统一写到一个文件中
#include <iostream>
#include <sys/types.h>
#include <dirent.h>
#include <vector>
#include <cstring>
using namespace std;
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;
}
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;
}