逆序存储小文件(一)——使用STL容器

将一个4M左右的文本文件内容逆序输出到另一个文本文件中,步骤如下:

1.使用文件输入流以只读方式打开源文件,创建一个容器,使用copy函数将流内容顺序复制到容器中;

2.创建一个文件输出流,制定输出目标,反向遍历容器,将容器内容写到流中。

 

代码如下:

#include <deque>
#include <vector>
#include <list>
#include <iostream>
#include <ctime>
#include <memory>
#include <fstream>
#include <iterator>
using namespace std;

template<typename T, template<typename U, typename=allocator<U>> class seq>
void ReverseStoreFile(const char* pSrcFile, const char* pDestFile)
{
	if(!pSrcFile || !pDestFile) return;
	
	time_t tBegin = time(0);
	
	seq<T> seqCh;

	ifstream in(pSrcFile, ios::in);
	copy(istream_iterator<char>(in), istream_iterator<char>(), back_inserter(seqCh));

	ofstream out(pDestFile, ios::out);
	copy(seqCh.rbegin(), seqCh.rend(), ostream_iterator<char>(out));
	
	time_t tEnd = time(0);
	cout<<typeid(seqCh).name()<<" time="<<tEnd - tBegin<<endl;
}

int main()
{
	ReverseStoreFile<char, std::deque>("in.txt", "deque_out.txt");

	ReverseStoreFile<char, std::vector>("in.txt", "vector_out.txt");

	ReverseStoreFile<char, std::list>("in.txt", "list_out.txt");
	return 0;
}


输出结果如下:

输出结果如下:

该方法存在性能问题,不适合操作大文件,而且不支持中文(iostream以字节为单位操作)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值