利用fstream实现输出到磁盘的迭代器

今天上午在这鼓弄着写了个输出到文件的iterator,它直接利用C++中的fstream中的对象实现,技术含量不是很高,自己也利用C语言函数,采用C++面向对象的思想也进行了实现。通过这些代码的编写,感触很深,觉得自己写代码太吃力,主要表现在写的太少,以前写过的一些东西也忘了,代码这个东西得多写才能记住,即使记住了一段时间不用又忘了,每次都是丢了拾,拾了再丢。哎,痛苦。所以从现在开始得开始好好总结自己写代码的一些东西,以备后续能够较好的整理。现在把实现的代码粘贴如下:代码为利用fstream实现的输出到磁盘的迭代器。

#include "stdafx.h"

#include <iostream>

#include <fstream>

#include <vector>

#include <deque>

#include <algorithm>

using namespace std ;

 

template<typename T>

class OutFile_iterator

{

protected:

       ofstream* outFile ;

       const char* s ;      

public://迭代器的几种必需指针

       typedef output_iterator_tag  iterator_category ;

       typedef void                 value_type ;

       typedef void                 difference_type ;

       typedef void                 pointer ;

       typedef void                 reference ;

       OutFile_iterator(ofstream& o) : outFile(&o),s(0) {}

       OutFile_iterator(ofstream& o , const char *c):outFile(&o), s(c){}

       OutFile_iterator<T> &operator = (const T& value)

       {

              *outFile << value ;

              if (s)

              {

                     *outFile << s ;

              }

              return *this ;

       }

       OutFile_iterator<T>& operator*() {return *this ;}//重载如下运算符,对于其实现很重要

       OutFile_iterator<T>& operator++() {return *this ;}

       OutFile_iterator<T>& operator++(int) {return *this ;}

 

};

 

 

int main(int argc, char* argv[])

{

       ofstream outfile ;

       outfile.open("test.txt" , ofstream::app) ;

       OutFile_iterator<char *> outite(outfile , "  ");

 

       char* s[6] = {"ssss" , "tttt" , "rrrr" , "iiii" , "nnnn" , "gggg"};

       vector<char *> cv(s , s+6) ;

       copy(cv.begin() , cv.end() , outite) ;

       outfile << '/n' ;

       outfile.close() ;

 

       return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值