现在的位置: 首页 > 综合 > 正文

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

2013年03月08日 ⁄ 综合 ⁄ 共 1554字 ⁄ 字号 评论关闭

今天上午在这鼓弄着写了个输出到文件的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;

}

抱歉!评论已关闭.