[C/C++标准库]_[初级]_[使用fstream合并文本文件]

来源:互联网 发布:nodejs mysql 中间件 编辑:程序博客网 时间:2024/06/08 21:35


场景:

1. 就是合并文本文件,并且从第2个文件起不要合并第一行.

2. 多加了一个功能,就是支持2个以上的文件合并.

3. 问题: http://ask.csdn.net/questions/192151



只能说很简单: 基础不过关吧,这位同学,也有可能不是开发的,放这里也是为了培训基础差的.

test.cpp

#include <fstream>#include <string>#include <iostream>using namespace std;//最后一个参数是输出文件.//支持多余2个的文件合并//用法,命令行: test.exe 1.txt 2.txt  output.txtint 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;}


1 0
原创粉丝点击