关于C++(MFC)写入TXT文件

关于C++(MFC)写入TXT文件

// 写入TXT文件
void WriteToText(CString sFileFullPathName, CString sLine);

// 读取TXT文件
CString ReadFromText(CString sFileFullPathName);


// ------------------------------------------------------------------
// 写入TXT文件
// add by jzh 2009-07-06
// ------------------------------------------------------------------
void CommFunc::WriteToText(CString sFileFullPathName, CString sLine)
{
  CStdioFile file; 
  int iFlag;
  if (FileIsExist(sFileFullPathName))
  {
      iFlag = 0;
  }
  else
  {
      iFlag = 1;
  }

  if (iFlag == 0)
  {
    file.Open(_T(sFileFullPathName), CFile::modeReadWrite); 
  }
  else
  {
      file.Open(_T(sFileFullPathName), CFile::modeCreate|CFile::modeReadWrite);
  }
    file.SeekToEnd();
  file.WriteString(sLine); 
  file.Close(); 
}

// ------------------------------------------------------------------
// 读取TXT文件
// add by jzh 2009-07-20
// ------------------------------------------------------------------
CString CommFunc::ReadFromText(CString sFileFullPathName)
{
  CString sLine;
  CString sReturn; 
  sLine = ""; 
    sReturn = "";

  if (!FileIsExist(sFileFullPathName))
  {
    MessageBox(NULL, "文件不存在", TEXT("提示"), MB_OK);
    return "";
  }

  CStdioFile file; 
    file.Open(sFileFullPathName, CFile::modeRead); //打开文件 只读模式 

  while(file.ReadString(sLine))  //一次读取一行 
  { 
    sReturn += sLine;
  } 
    file.Close(); //关闭文件
  return sReturn;
}

 

发表回复

您的电子邮箱地址不会被公开。