使用ifstream ofstream copy快速处理文本

c++对文件的操作分成了两种类型,一种是“文本"文件,另一种是"二进制"文件;文本文件是人类能够看懂的,二进制文件是机器文件是我们看不懂的。

这样区分对我们对文件的处理有了更明确的方向,加快了文件的处理和使得代码更加简洁。

如果说我们需要把容器中的数据写到一个流中(本次就是文件流了,其它流也可以),或者是把流中的数据(本次为文件流)写到一个容器中,代码可

以向下面这样简化。

 

#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
#include <sstream>

int main(int argc,char **argv)
{
	if (argc != 3) {
		std::cout << "Usage: " << argv[0] << " <outFileName> <inFileName>" << std::endl;
		return -1;
	}

	std::ofstream outFileStream(argv[1]);
	std::vector<int> vecInt{ 123,34,231,343,454,343,565,565 };
	std::copy(vecInt.begin(), vecInt.end(), std::ostream_iterator<int>(outFileStream, " "));
	outFileStream.close();
	
	std::ifstream inFileStream(argv[2]);
	vecInt.clear();
#if 1
	//直接在容器后面插入
	std::copy(std::istream_iterator<int>(inFileStream), std::istream_iterator<int>(), std::back_inserter(vecInt));//直接在容器后面插入
	std::copy(std::istream_iterator<int>(inFileStream), std::istream_iterator<int>(), std::back_inserter(vecInt));

           如果是set或者map之类的用std::inserter(容器对象,迭代器位置)

#else
	//从vecInt的开始位置覆盖,数量为文件流中int数据的数量与容器大小之间小的那一个;注意如果vecInt限定了容器大小,且大小小于文件流中的int数据量则会//从vecInt的开始位置覆盖,数量为文件流中int数据的数量与容器大小之间小的那一个;注意如果vecInt限定了容器大小,且大小小于文件流中的int数据量则会
	//有不可预料的结果//有不可预料的结果
	std::copy(std::istream_iterator<int>(inFileStream), std::istream_iterator<int>(), vecInt.begin());std::copy(std::istream_iterator<int>(inFileStream), std::istream_iterator<int>(), vecInt.begin());
#endif
	//输出到终端//输出到终端
	std::copy(vecInt.begin(), vecInt.end(), std::ostream_iterator<int>(std::cout, " "));
	inFileStream.close();
	::getchar();
	return 0;
}

另个在VS中这样设置,可以让生成的程序可以直接在windows上运行,不需要附带运行dll(一般为mscvp140.dll,ucrtbase.dll,vcruntime140.dll),我使用的VS是2015

选中工程右键选择属性,选择c/c++中的代码生成,选择运行库为多线程MT(release版本)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值