现在的位置: 首页 > 综合 > 正文

VC_文件操作_API和MFC操作文件

2014年01月06日 ⁄ 综合 ⁄ 共 1243字 ⁄ 字号 评论关闭
用Win32API函数操作文件:
 
1.保存文件
 首先用CreateFile 打开文件,然后调用WriteFile将数据写入到文件当中。
   
2.读取文件
   首先用CreateFile 打开文件,然后调用ReadFile读取数据到ch字符数组中。
---------------------------------------------------------------------------------
MFC中操作文件的类Cfile
1.写入文件
   首先构造一个CFile对象:CFile file("CFile.txt",CFile::modeCreate | CFile::modeWrite);
   然后调用CFile对象的Write方法写入数据:
 file.Write("teshorse@hotmail.com", strlen("teshorse@hotmail.com"));
   最后关闭文件:file.Close();
 
 
自己测试过的代码,分别使用API和MFC两种方式

#if (USE_MODE==WINDOWS_API)
   U32 NumBytesRead;
   HANDLE hFile = CreateFile("D:\\My Documents\\桌面\\cmd.txt", GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
   U32 FileSize = GetFileSize(hFile, NULL);
   char * pFile = malloc(FileSize);
   ReadFile(hFile, pFile, FileSize, &NumBytesRead, NULL);
   MORRIS_TRACE((LPCSTR)pFile);
   CloseHandle(hFile);

   //if close must free pfile
   //free(pFile);
  
#elif (USE_MODE==WINDOWS_MFC)
 U32 t_wtmp;
 CString m_strElement;
 LPCSTR lpszPath = "D:\\My Documents\\桌面\\cmd.txt";
 ReadFilePathName=lpszPath;

 CFile fp;
 if(!(fp.Open((LPCTSTR)ReadFilePathName,CFile::modeRead)))
 {
  MORRIS_TRACE("Open file failed!");
  return;
 }
 fp.SeekToEnd();
 U32 fplength=fp.GetLength();
 U8* fpBuff;
 fpBuff=new U8[fplength];
 fp.SeekToBegin();
 if(fp.Read(fpBuff,fplength)<1)
 {
  fp.Close();
  return;
 }
 fp.Close();

 MORRIS_TRACE(fpBuff);

抱歉!评论已关闭.