MFC implements the method of appending data to the end of a file

  • 2020-05-05 11:32:59
  • OfStack

This article illustrates how MFC implements appending data to the end of a file. Share with you for your reference. The details are as follows:


BOOL CDelDlg::WritetoFile(CString sValue)
{
  CString sFile = GetExePath() + "\\1.log";
  CStdioFile file;
  if(file.Open(sFile, CFile::modeCreate | CFile::modeWrite | CFile::modeNoTruncate))
  {
    file.SeekToEnd(); //  Move the file pointer to the end 
    file.WriteString(sValue);
    file.Close();
  }
  return FALSE;
}

The code for GetExePath() is as follows:


//  Returns the directory where the executable resides ( It doesn't include the last one '\')
CString GetExePath()
{
  char sFileName[256] = {0};
  CString sPath = _T("");
  GetModuleFileName(AfxGetInstanceHandle(), sFileName, 255);
  sPath.Format("%s", sFileName);
  int pos = sPath.ReverseFind('\\');
  if(pos != -1)
    sPath = sPath.Left(pos);
  else
    sPath = _T("");
  return sPath;
}

I hope this article has been helpful to your MFC programming.


Related articles: