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();
}

写的不好,请大家批评
原文地址:https://www.cnblogs.com/tianfu/p/1560417.html