fstream如何将两份相似的文件合并,例如将1.txt和2.txt合并,1.txt和2.txt里面的内容是表格形式,表头一样,内容不一样,如何将其合并,合并后内容连在一起,表头只有一份
2条回答 默认 最新
关注
1.顺便写了一篇blog. http://blog.csdn.net/infoworld/article/details/46758199
#include <fstream> #include <string> #include <iostream> using namespace std; //最后一个参数是输出文件. //支持多余2个的文件合并 //用法,命令行: test.exe 1.txt 2.txt output.txt int main(int argc, char const *argv[]) { cout << "usage1: test.exe 1.txt 2.txt output.txt" << endl; cout << "usage2: test.exe 1.txt 2.txt ... output.txt" << endl; if(argc <= 3) return -1; bool first_line_readed = false; ofstream fout(argv[argc-1], ios::out); for(int i = 1 ; i< argc - 1; ++i) { ifstream fin(argv[i]); string str; int line_number = 0; while(getline(fin,str)) { if(!line_number) { if(!first_line_readed) { first_line_readed = true; str.append("\n"); fout.write(str.c_str(),str.size()); } }else { str.append("\n"); fout.write(str.c_str(),str.size()); } line_number++; } } cout << "finish..." << argv[argc-1] << endl; return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报