[C/C++标准库]_[0基础]_[使用fstream合并文本文件]


场景:

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

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

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



仅仅能说非常easy: 基础只是关吧,这位同学,也有可能不是开发的,放这里也是为了培训基础差的.

test.cpp

#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("
");
					fout.write(str.c_str(),str.size());
				}				
			}else
			{
				str.append("
");
				fout.write(str.c_str(),str.size());
			}

			line_number++;
		}
	}
	cout << "finish..." << argv[argc-1] << endl;
	return 0;
}


原文地址:https://www.cnblogs.com/claireyuancy/p/6943267.html