计算机二级考试C语言辅导:剖析VC中的文件操作3

来源:微学计算机考试频道发布时间:2008-08-27
vc中的文件操作
  File Operations in VC
  1:Find the file
  CString strFileName;
  CFileFind finder;
  BOOL bWorking=finder.FindFile(”c:\windows\*.cab”);
  if(bWorking)
  {
  bWorking=finder.FindNextFile();
  strFileName=finder.GetFileName();//or finder.GetFileTitle();
  }
  2:Open or Save file
  CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT|OFN_ALLOWMULTISELECT,”All Files(*.*)|*.*||”
  ,AfxGetMainWnd());
  3:Read and Write File
  //Read File
  char cRead[10]; CFile mFile(_T(”test.txt”),CFile::modeRead);
  if(mFile.GetLength()<2)
  return ;
  mFile.Read(cRead,10);
  mFile.Close();
  //Write File:
  CFile mFile(_T(”test.txt”),CFile::modeWrite|CFile:modeCreate);mFile.Write(cRead,10);
  mFile.Flush();
  mFile.Close();
  More Powerful Class: CArchive
  //Write
  CString strTemp;
  CFile mFile;
  mFile.Open(”c:\test.txt”,CFile::modeWrite|CFile::modeNoTruncate|CFile::modeCreate);
  CArchive ar(&mFile,CArchive::store);
  ar<
   ar.Close();
  mFile.Close();
  //Read
  CFile mFile;
  if(mFile.Open(”c:\test.txt”,CFile::modeRead)==0)
  return;
  CArchive ar(&mFile,CArchive::load);
  ar>>strTemp;
  ar.Close();
  mFile.Close();
  using CArchive, you can also to WriteObject,ReadObject,WriterClass,ReadClass
  if you only to read or write a simple line string, use CStdioFile
  CStdioFile mFile;
  CFileException mExcept;
  mFile.Open(”c:\test.txt”,CFile::modeWrite,&mExcept);
  CString str=”hello world”;
  mFile.WriteString(string);
  mFile.Close();
  4:Using temp file
  char szTempPath[_MAX_PATH],szTempFile[_MAX_PATH];
  GetTempPath(_MAX_PATH,szTempPath);
  GetTempFileName(szTempPath,_T(”my_”),0,szTempFile);
  CFile m_tempFile(szTempFile,CFile::modeCreate|CFile::modeWrite);
  char m_char='a';
  m_TempFile.Write(&m_char,2);
  m_TempFile.Close();
  5:Copy or remove file:
  For in the MFC there is no methods or classes,so use SDK functions: CopyFile(),DeleteFile(),CreateDirectory(),MoveFile(