Chinaunix首页 | 论坛 | 博客
  • 博客访问: 339029
  • 博文数量: 88
  • 博客积分: 1695
  • 博客等级: 上尉
  • 技术积分: 1380
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-06 15:48
个人简介

喜欢美食, 旅行..

文章分类

全部博文(88)

文章存档

2014年(2)

2013年(12)

2012年(14)

2010年(8)

2009年(52)

我的朋友

分类: C/C++

2013-08-05 20:01:09

原理很简单, 利用标准库的文件流, 逐行读取文本文件, 然后每行一个 string 放进 vector 容器里面去.

行操作就可以简单的操作每一个 string 即可. 
列操作可以操作每一个 string 的下标即可.

  1. #pragma once

  2. #include <string>
  3. #include <vector>
  4. #include <fstream>

  5. template< class _Elem >
  6. class CTxtFileEditor :
  7.     public std::vector<basic_string<_Elem, char_traits<_Elem>, allocator<_Elem>>>
  8. {
  9.     typedef basic_ifstream<_Elem, char_traits<_Elem> > IFStream;
  10.     typedef basic_ofstream<_Elem, char_traits<_Elem> > OFStream;
  11.     typedef basic_string<_Elem, char_traits<_Elem>, allocator<_Elem>> String;
  12.     String m_wscPathFile;
  13. public:
  14.     CTxtFileEditor(const String pathFile)
  15.     {
  16.         ReadViaLocalFile(pathFile);
  17.     }
  18.     CTxtFileEditor(const _Elem * ptrPathFile)
  19.     {
  20.         const String pathFile = ptrPathFile;
  21.         ReadViaLocalFile(pathFile);
  22.     }
  23.     bool ReadViaLocalFile(const String pathFile)
  24.     {
  25.         if ( pathFile.empty() )
  26.             return false;

  27.         m_wscPathFile = pathFile;

  28.         std::locale old = std::locale::global(std::locale("chs"));
  29.         IFStream fin(m_wscPathFile.c_str());
  30.         std::locale::global(old);

  31.         String line;
  32.         while( getline(fin,line) )
  33.         {
  34.             push_back( line );
  35.         }

  36.         fin.close();

  37.         return true;
  38.     }
  39.     bool UpdateLocalFile()
  40.     {
  41.         if ( m_wscPathFile.empty() )
  42.             return false;
  43.         std::locale old = std::locale::global(std::locale("chs"));
  44.         OFStream fout( m_wscPathFile.c_str() );
  45.         std::locale::global(old);
  46.         for ( iterator it = begin(); it != end(); ++it )
  47.         {
  48.             String content = *it + static_cast<_Elem>('\n');
  49.             fout.write ( content.c_str(),static_cast<std::streamsize>(content.size()) );
  50.         }
  51.         fout.close();
  52.         return true;
  53.     }
  54. };

  55. typedef CTxtFileEditor< char > CTxtFileEditorA;
  56. typedef CTxtFileEditor< wchar_t > CTxtFileEditorW;

阅读(633) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~