zoukankan      html  css  js  c++  java
  • VC文件读写

    用惯了标准C++的iostream,所以很喜欢用ifstream和ofstream来读写文件,如:
    bool TPub::readFileToString(const string &strFileName, string &strTarget)
    {
           locale &loc=locale::global(locale(locale(),"",LC_CTYPE)); 
           ifstream in(strFileName.c_str(), ios::in);
           if (!in.is_open())
                  return false;
           //in.unsetf(ios_base::skipws);
           locale::global(loc); 
           strTarget = string((istreambuf_iterator<char>(in)), istreambuf_iterator<char>());
           return true;
    };
    //---------------------------------------------------------------------------
    bool TPub::writeStringToFile(const string &strSource, const string &strFileName)
    {
           ofstream out(strFileName.c_str(), ios::out|ios::trunc);
           if (!out.is_open())
                  return false;
           out << strSource;
          return true;
    };
    直至有一天和一个朋友配合一起写一个WIN CE上的MP3播放器,其中有涉及到读文件的操作,我用的是ifstream以及其方法read,发现读取很慢,并且在VS2005上ifstream还有中文路径以及中文内容读取乱码的问题,这才想到了CFile(说实在的,我不喜欢用MICROSOFT的这个东西),没有想到速度快了很多,哈哈,看来ifstream有作缓存,速度较慢,CFile在这方面做了优化。

    下面是另外两个有关CFile读写文件的操作方法:

    void TextDialog::readFile(CString strFileName, CString& str)
    {
          DWORD dwAttr = ::GetFileAttributes(strFileName); 
          if (dwAttr == 0xffffffff)  
          {
                 return;
          } 
          CFile SourceFile;//数据文件
          CString SourceData;//定义一临时变量保存一条记录
          CFileException ex;
          SourceFile.Open(strFileName, CFile::modeRead | CFile::shareDenyWrite, &ex);
          CArchive ar(&SourceFile,CArchive::load);
          while(NULL != ar.ReadString(SourceData))//循环读取文件,直到文件结束
          { 
                 str += SourceData+"\r\n";
                 if(str == "")
                      continue;//跳过文件头部的提示信息
          }
          SourceFile.Close();
    }

    void TextDialog::writeFile(CString str, CString strFileName)
    {
          CFile file;
          file.Open(strFileName, CFile::modeCreate|CFile::modeWrite);
          file.Write(str.GetBuffer(0), str.GetLength());
          file.Close();
    }

    写的不好,请大家批评
  • 相关阅读:
    js 计时器小练-20160601
    数位dp入门学习之路(正常枚举“过渡到”dfs枚举)
    An easy problem
    牌型种类 蓝桥杯
    带分数(穷举法) 蓝桥杯赛题
    表达式的转换----->中缀表达式转后缀表达式
    map 的使用
    netsatat 的使用
    两个矩形不相交
    前缀和
  • 原文地址:https://www.cnblogs.com/tianfu/p/1560417.html
Copyright © 2011-2022 走看看