mfc文件操作

MFC文件操作总结

MFC文件操作大全

 
1.创建文件夹
CreateDirectory(%%1,NULL);

2.创建文件
CFile file; 
file.Open(%%1,CFile::modeCreate|CFile::modeWrite); 

3.删除文件
DeleteFile(%%1);

4.删除文件夹
RemoveDirectory(%%1); 

5.删除一个目录下所有的文件夹
CFileFind finder; 
BOOL bWorking = finder.FindFile(%%1+"//*.*"); 
while (bWorking)
{
bWorking = finder.FindNextFile();
if (finder.IsDirectory())
{
RemoveDirectory(finder.GetFilePath());
}


6.清空文件夹
RemoveDirectory(%%1);
CreateDirectory(%%1,NULL);

7.读取文件
char sRead[1024];
CFile mFile(_T(%%1),CFile::modeRead);
while (sRead!=null)
{
mFile.Read(sRead,1024);
CString %%2(sRead);
%%3
  
 
 

 

2

回复:MFC文件操作大全

 
8.写入文件
CFile mFile(_T(%%1), CFile::modeWrite|CFile::modeCreate);
mFile.Write(%%2,sizeof(%%2));
mFile.Flush();
mFile.Close(); 

9.写入随机文件
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();
//循环写入多个值
strTempA;
int i;
int nCount=6;
//共有6个文件名需要保存
for (i=0;i{strTemp.Format("%d",i);
strTempA=文件名;
//文件名可以从数组,列表框等处取得.
::WritePrivateProfileString("UseFileName","FileName"+strTemp,strTempA,
c://usefile//usefile.ini);
}
strTemp.Format("%d",nCount);
::WritePrivateProfileString("FileCount","Count",strTemp,"c://usefile//usefile.ini");
//将文件总数写入,以便读出.
//读出
nCount=::GetPrivateProfileInt("FileCount","Count",0,"c://usefile//usefile.ini");
for(i=0;i{strTemp.Format("%d",i);
strTemp="FileName"+strTemp;
::GetPrivateProfileString("CurrentIni",strTemp,"default.fil", strTempA.GetBuffer(MAX_PATH),MAX_PATH,"c://usefile//usefile.ini");
//使用strTempA中的内容.


10.读取文件属性
dwAttrs   =   GetFileAttributes(%%1); 
if   (dwAttrs   &   FILE_ATTRIBUTE_READONLY)     {   
   %%2
}     
if   (NORMAL & FILE_ATTRIBUTE_READONLY){   
   %%3
}   

11.写入属性
SetFileAttributes(szNewPath,dwAttrs | FILE_ATTRIBUTE_READONLY);   

12.枚举一个目录下所有文件夹
CFileFind finder; 
BOOL bWorking = finder.FindFile(%%1+"//*.*"); 
while (bWorking) { 
bWorking = finder.FindNextFile();
if(finder.IsDirectory()){
CString %%1=finder.GetFilePath();
%%2
}


13.复制文件夹
WIN32_FIND_DATA FileData; 
HANDLE hSearch; 
DWORD dwAttrs; 
char szDirPath[] = %%2; 
char szNewPath[MAX_PATH]; 
char szHome[MAX_PATH]; 
BOOL fFinished = FALSE; 
if (!CreateDirectory(szDirPath, NULL)) {
//不能创建新的目录 
   return;
}
hSearch = FindFirstFile(%%1+"//*.*", &FileData); 
if (hSearch == INVALID_HANDLE_VALUE) { 
   return; 

while (!fFinished) { 
  
 
 

 

3

回复:MFC文件操作大全

 
   lstrcpy(szNewPath, szDirPath); 
   lstrcat(szNewPath, FileData.cFileName); 
   if (CopyFile(FileData.cFileName, szNewPath, FALSE)) { 
   dwAttrs = GetFileAttributes(FileData.cFileName); 
   if (!(dwAttrs & FILE_ATTRIBUTE_READONLY)) { 
   SetFileAttributes(szNewPath, 
   dwAttrs | FILE_ATTRIBUTE_READONLY); 
   } 
   } 
   else { 
   //不能复制文件
   return; 
   } 
   if (!FindNextFile(hSearch, &FileData)) { 
   if (GetLastError() == ERROR_NO_MORE_FILES) { 
   //遍历文件夹完成 
   fFinished = TRUE; 
   } 
   else { 
   //找不到下一个文件
   return; 
   } 
   } 

FindClose(hSearch); 

14.复制一个目录下所有的文件夹到另一个文件夹下
WIN32_FIND_DATA FileData; 
HANDLE hSearch; 
DWORD dwAttrs; 
char szDirPath[] = %%2; 
char szNewPath[MAX_PATH]; 
char szHome[MAX_PATH]; 
BOOL fFinished = FALSE; 
if (!CreateDirectory(szDirPath,NULL)) 
{
//不能创建新的目录 
return;
}
BOOL bWorking = finder.FindFile(%%1+"//*.*"); 
while (bWorking) 

bWorking = finder.FindNextFile();
if(finder.IsDirectory()){
hSearch = FindFirstFile(finder.GetFilePath()+"//*.*", &FileData); 
if (hSearch == INVALID_HANDLE_VALUE) 

return; 

while (!fFinished) 

lstrcpy(szNewPath, szDirPath); 
lstrcat(szNewPath, FileData.cFileName); 
if (CopyFile(FileData.cFileName, szNewPath, FALSE)) 

dwAttrs = GetFileAttributes(FileData.cFileName); 
if (!(dwAttrs & FILE_ATTRIBUTE_READONLY)) 

SetFileAttributes(szNewPath, 
dwAttrs | FILE_ATTRIBUTE_READONLY); 


else 

//不能复制文件
return; 

if (!FindNextFile(hSearch, &FileData)) 

if (GetLastError() == ERROR_NO_MORE_FILES) 

//遍历文件夹完成 
fFinished = TRUE; 

else 

//找不到下一个文件
return; 



FindClose(hSearch);
}


15.移动文件夹
WIN32_FIND_DATA FileData; 
HANDLE hSearch; 
DWORD dwAttrs; 
char szDirPath[] = %%2; 
char szNewPath[MAX_PATH]; 
char szHome[MAX_PATH]; 
BOOL fFinished = FALSE; 
if (!CreateDirectory(szDirPath, NULL)) 
{
//不能创建新的目录 
return;
}
hSearch = FindFirstFile(%%1+"//*.*", &FileData); 
if (hSearch == INVALID_HANDLE_VALUE) 

return; 

while (!fFinished) 

lstrcpy(szNewPath, szDirPath); 
lstrcat(szNewPath, FileData.cFileName); 
if (CopyFile(FileData.cFileName, szNewPath, FALSE)) 

dwAttrs = GetFileAttributes(FileData.cFileName); 
if (!(dwAttrs & FILE_ATTRIBUTE_READONLY)) 

SetFileAttributes(szNewPath, 
dwAttrs | FILE_ATTRIBUTE_READONLY); 


else 

//不能复制文件
return; 

if (!FindNextFile(hSearch, &FileData)) 

if (GetLastError() == ERROR_NO_MORE_FILES) 

//遍历文件夹完成 
fFinished = TRUE; 

else 

//找不到下一个文件
return; 



FindClose(hSearch); 
RemoveDirectory(%%1);
  
 
 

 

4

回复:MFC文件操作大全

 
16.移动一个文件夹下所有的文件夹到另一个目录下
WIN32_FIND_DATA FileData; 
HANDLE hSearch; 
DWORD dwAttrs; 
char szDirPath[] = %%2; 
char szNewPath[MAX_PATH]; 
char szHome[MAX_PATH]; 
BOOL fFinished = FALSE; 
if (!CreateDirectory(szDirPath,NULL)) 
{
//不能创建新的目录 
return;
}
BOOL bWorking = finder.FindFile(%%1+"//*.*"); 
while (bWorking) 

bWorking = finder.FindNextFile();
if(finder.IsDirectory()){
hSearch = FindFirstFile(finder.GetFilePath()+"//*.*", &FileData); 
if (hSearch == INVALID_HANDLE_VALUE) 

return; 

while (!fFinished) 

lstrcpy(szNewPath, szDirPath); 
lstrcat(szNewPath, FileData.cFileName); 
if (CopyFile(FileData.cFileName, szNewPath, FALSE)) 

dwAttrs = GetFileAttributes(FileData.cFileName); 
if (!(dwAttrs & FILE_ATTRIBUTE_READONLY)) 

SetFileAttributes(szNewPath, 
dwAttrs | FILE_ATTRIBUTE_READONLY); 


else 

//不能复制文件
return; 

if (!FindNextFile(hSearch, &FileData)) 

if (GetLastError() == ERROR_NO_MORE_FILES) 

//遍历文件夹完成 
fFinished = TRUE; 

else 

//找不到下一个文件
return; 



FindClose(hSearch);
RemoveDirectory(finder.GetFilePath().GetBuffer(0));
}


17.以一个文件夹的框架在另一个目录创建文件夹和空文件
WIN32_FIND_DATA FileData; 
HANDLE hSearch; 
DWORD dwAttrs; 
char szDirPath[] = %%2; 
char szNewPath[MAX_PATH]; 
char szHome[MAX_PATH]; 
BOOL fFinished = FALSE; 
if (!CreateDirectory(szDirPath, NULL)) 
{
//不能创建新的目录 
return;
}
hSearch = FindFirstFile(%%1+"//*.*", &FileData); 
if (hSearch == INVALID_HANDLE_VALUE) 

return; 

while (!fFinished) 

lstrcpy(szNewPath, szDirPath); 
lstrcat(szNewPath, FileData.cFileName); 
HANDLE hFile=CreateFileHandle hFile=CreateFile(szNewPath,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN,NULL);
if(!hFile)
{
//不能创建文件
return;

if (!FindNextFile(hSearch, &FileData))

if (GetLastError() == ERROR_NO_MORE_FILES) 

//遍历文件夹完成 
fFinished = TRUE; 

else 

//找不到下一个文件
return;



FindClose(hSearch); 

18.复制文件
CopyFile(%%1,%%2,true);
  
 
 

 

5

回复:MFC文件操作大全

 
19.复制一个文件夹下所有的文件到另一个目录
//#include <string>
using std::string;
char sep='/';
#ifdef _WIN32
sep='//';
#endif
CFileFind finder; 
BOOL bWorking = finder.FindFile(%%1+"//*.*"); 
while (bWorking) 

bWorking = finder.FindNextFile();
if(!finder.IsDirectory() || finder.IsDots()){
string s(finder.GetFileName());
CString sourcefile(%%1);
if(s.rfind(sep,s.length())!=string::npos)
{
sourcefile=sourcefile+"//"+s.substr(i+1,s.length()-i);
CString targetfile(s.substr(i+1,s.length()-i));
targetfile=%%2+"//"+targetfile/;
CopyFile(sourcefile.GetBuffer(0),targetfile.GetBuffer(0),true);
}
}


20.提取扩展名
CString path(%%1);
CString %%2=path.Mid(path.ReverseFind('.'));

21.提取文件名
CString path(%%1);
CString %%2=path.Mid(path.ReverseFind('//')+1);

22.提取文件路径
char appName[MAX_PATH];
GetModualFileName(NULL,appName,MAX_PATH);
  
 
 

 

6

回复:MFC文件操作大全

 
23.替换扩展名
//#include <string>
using std::string;
string s(%%1);
string newExt(%%2);
string::size_type i=s.rfind('.',s.length());
if(i!=string::npos)
s.replace(i+1,newExt.length(),newExt);
CString %%3(s); 

24.追加路径
/*
#include <string>
#include <cstdlib>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
*/
using namespace std;
using namespace boost::filesystem;
try {
path p1=complete(path(%%2,native),
path(%%1,native));
path p2=system_complete(path(%%2,native));
CString %%3(p3);
}
catch(exception& e){
//e.what();


25.移动文件
MoveFile(%%1,%%2);
  
 
 

 

7

回复:MFC文件操作大全

 
26.移动一个文件夹下所有文件到另一个目录
//#include <string>
using std::string;
char sep='/';
#ifdef _WIN32
sep='//';
#endif
CFileFind finder; 
BOOL bWorking = finder.FindFile(%%1+"//*.*"); 
while (bWorking) 

bWorking = finder.FindNextFile();
if(!finder.IsDirectory() || finder.IsDots()){
string s(finder.GetFileName());
CString sourcefile(%%1);
if(s.rfind(sep,s.length())!=string::npos)
{
sourcefile=sourcefile+"//"+s.substr(i+1,s.length()-i);
CString targetfile(s.substr(i+1,s.length()-i));
targetfile=%%2+"//"+targetfile/;
MoveFile(sourcefile.GetBuffer(0),targetfile.GetBuffer(0),true);
}
}


27.指定目录下搜索文件
CString strFileTitle;
CFileFind finder;
BOOL bWorking = finder.FindFile ("C://windows//sysbkup//*.cab");
while(bWorking)
{
bWorking=finder.FindNextFile();
strFileTitle=finder.GetFileTitle();
}
  
 
 

 

8

回复:MFC文件操作大全

 
28.打开对话框
CFileDialog mFileDlg(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT|OFN_ALLOWMULTISELECT,"All Files (*.*)|*.*||",AfxGetMainWnd());
CString str(" ",10000);
mFileDlg.m_ofn.lpstrFile=str.GetBuffer(10000);
str.ReleaseBuffer();
POSITION mPos=mFileDlg.GetStartPosition();
CString pathName(" ",128);
CFileStatus status;
while(mPos!=NULL)
{
pathName=mFileDlg.GetNextPathName(mPos);
CFile::GetStatus( pathName, status );


29.文件分割
CFile m_File;
CString m_Filename,m_FileTitle,m_FilePath;
m_FileName=%%1;
char pBuf[4096];
if(m_File.Open(m_FileName,CFile::modeRead | CFile::shareDenyWrite))
{
m_FileName=m_File.GetPathName();
m_FileTitle=m_File.GetFileTitle();
DWORD FileLength=m_File.GetLength();
DWORD PartLength=FileLength/2+FileLength%2;
int nCount=1;
CString strName;
CFile wrFile;
DWORD ReadBytes;
while(true)
{
ReadBytes=m_File.Read(pBuf,PartLength);
strName.Format("%s%d",m_FIleTitle,nCount);
wrFile.Open(strName,CFile::modeWrite | CFile::modeCreate);
wrFile.Write(pBuf,ReadBytes);
wrFile.Close();
if(ReadBytes<PartLength)
break;
nCount++;
}
m_File.Close();
}
else
AfxMessageBox("不能打开文件");
  
 
 

 

9

回复:MFC文件操作大全

 
30.文件合并
//#include <string>
using std::string;
string s(%%1);
char sep='/';
#ifdef _WIN32
sep='//';
#endif
size_t sz=s.rfind(sep,s.length());
if(sz!=string::npos)
{
CFile Out;
CString strFilename(s.substr(i+1,s.length()-i));
if(Out.Open(%%2+"//"+strfilename,cfile::modewrite%7ccfile::modecreate)){
for(int i=1;i<=2;i++)
{
String Filename=%%%2+"//"+strfilename+atoi(i);
CFile In;
if(In.Open(Filename,CFile::modeRead)){
char cbBuffer[4096];
int nFilesize=In.GetLength();
while(nFilesize>0){
int nSize=sizeof(cbBuffer);
if(nSize>nFilesize)
nSize=nFilesize;
try{
In.Read(cbBuffer,nSize);
}
catch(CFileException *e){
char *lpMsgBuf;
if(FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,e->m_lOsError,
MAKELANGID(LANG_NEUTRAL,
SUBLANG_DEFAULT),
(LPSTR)&lpMsgBuf,0,NULL)>0){
AfxMessageBox(lpMsgBuf);
LocalFree(lpMsgBuf);
}
e->Delete();
return;
}
try{
Out.Write(cbBuffer,nSize);
}
catch(CFileException *e){
char *lpMsgBuf;
if(FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,e->m_lOsError,
MAKELANGID(LANG_NEUTRAL,
SUBLANG_DEFAULT),
(LPSTR)&lpMsgBuf,0,NULL)>0){
AfxMessageBox(lpMsgBuf);
LocalFree(lpMsgBuf);
}
e->Delete();
return;
}
nFilesize=nSize;
}
}
else
AfxMessageBox("不能打开"+Filename);
}
}
else
AfxMessageBox("不能创建输出文件");
}
  
 
 

 

10

回复:MFC文件操作大全

 
31.文件简单加密
//#include <string>
using std::string;
string s(%%1);
char sep='/';
#ifdef _WIN32
sep='//';
#endif
size_t sz=s.rfind(sep,s.length());
if(sz!=string::npos)
{
CFile Out,In;
int nFIlesize;
char *lpMsgBuf;
CString strFilename(s.substr(i+1,s.length()-i));
if(!in.Open(%%1,CFile::modeRead)){
//不能打开输入文件
return;
}
if(!Out.Open(%%2+"//enc_%22+strfilename,cfile::modewrite/ | CFile::modeCreate)){
//不能打开输出文件
return;
}
nFilesize=In.GetLength();
lpBuffer=new char[nFilesize];
if(lpBuffer==NULL){
//不能分配复制缓存
return;
}
CFileStatus rStatus;
In.GetStatus(%%1,rStatus);
try{
In.Read(cbBuffer,nFilesize);
}
catch(CFileException *e){
char *lpMsgBuf;
if(FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,e->m_lOsError,
MAKELANGID(LANG_NEUTRAL,
SUBLANG_DEFAULT),
(LPSTR)&lpMsgBuf,0,NULL)>0){
AfxMessageBox(lpMsgBuf);
LocalFree(lpMsgBuf);
}
e->Delete();
return;
}
for(int i=0;i<nFilesize;i++)
{
int ibt=lpBuffer[i];
ibt+=100;
ibt%=256;
bpBuffer[i]=(char)ibt;
}
try{
Out.Write(cbBuffer,nFilesize);
}
catch(CFileException *e){
char *lpMsgBuf;
if(FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,e->m_lOsError,
MAKELANGID(LANG_NEUTRAL,
SUBLANG_DEFAULT),
(LPSTR)&lpMsgBuf,0,NULL)>0){
AfxMessageBox(lpMsgBuf);
LocalFree(lpMsgBuf);
}
e->Delete();
return;
}
Out.Close();
//In.Close();
CFile::SetStatus(%%2+"//enc_%22+strfilename,rstatus);
 delete[] lpBuffer;
}
  
 
 

 

11

回复:MFC文件操作大全

 
32.文件简单解密
//#include <string>
using std::string;
string s(%%1);
char sep='/';
#ifdef _WIN32
sep='//';
#endif
size_t sz=s.rfind(sep,s.length());
if(sz!=string::npos)
{
CFile Out,In;
int nFIlesize;
char *lpMsgBuf;
CString strFilename(s.substr(i+1,s.length()-i));
if(!in.Open(%%2+"//enc_%22+strfilename,cfile::moderead)){
//不能打开输入文件
return;
}
if(!Out.Open(%%1,CFile::modeWrite | CFile::modeCreate)){
//不能打开输出文件
return;
}
nFilesize=In.GetLength();
lpBuffer=new char[nFilesize];
if(lpBuffer==NULL){
//不能分配复制缓存
return;
}
CFileStatus rStatus;
In.GetStatus(%%2+"//enc_%22+strfilename,rstatus);
 try{
In.Read(cbBuffer,nFilesize);
}
catch(CFileException *e){
char *lpMsgBuf;
if(FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,e->m_lOsError,
MAKELANGID(LANG_NEUTRAL,
SUBLANG_DEFAULT),
(LPSTR)&lpMsgBuf,0,NULL)>0){
AfxMessageBox(lpMsgBuf);
LocalFree(lpMsgBuf);
}
e->Delete();
return;
}
for(int i=0;i<nFilesize;i++)
{
int ibt=lpBuffer[i];
ibt-=100;ibt+=256;
ibt%=256;
bpBuffer[i]=(char)ibt;
}
try{
Out.Write(cbBuffer,nFilesize);
}
catch(CFileException *e){
char *lpMsgBuf;
if(FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,e->m_lOsError,
MAKELANGID(LANG_NEUTRAL,
SUBLANG_DEFAULT),
(LPSTR)&lpMsgBuf,0,NULL)>0){
AfxMessageBox(lpMsgBuf);
LocalFree(lpMsgBuf);
}
e->Delete();
return;
}
Out.Close();
//In.Close();
CFile::SetStatus(%%1,rStatus);
delete[] lpBuffer;
}
  
 
 

 

12

回复:MFC文件操作大全

 
33.读取ini文件属性
CStdioFile inifile(%%1,CFile::modeRead);
CString path = inifile.GetFilePath();
inifile.Close();
char key[1024];
DWORD bytes = GetPrivateProfileString(%%2,%%3,%%4,key,1024,path);
if(bytes < 1024)
key[bytes] = '/0';
CString %%5(key); 

34.合并一个文件下所有的文件
CString Directory=%%1+"*.*";
CFileFind FFile;
CFile Out;
if(Out.Open(%%2,CFile::modeWrite|CFile::modeCreate)){
BOOL bFound=FFile.FindFile(Directory);
while(bFound)
{
bFound=FFile.FileNextFile();
if(!FFile.IsDirectory() && !FFile.IsDots())
{
CString Filename=FFile.GetFileName();
CFile In;
if(In.Open(Filename,CFile::modeRead)){
char cbBuffer[4096];
int nFIlesize=In.GetLength();
while(nFIlesize>0){
{
int nSize=sizeof(cbBuffer);
if(nSize>nFilesize)
nSize=nFilesize;
try {
In.Read(cbBuffer,nSize);
}
catch(CFileException *e){
char *lpMsgBuf;
if(FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,e->m_lOsError,
MAKELANGID(LANG_NEUTRAL,
SUBLANG_DEFAULT),
(LPSTR)&lpMsgBuf,0,NULL)>0){
AfxMessageBox(lpMsgBuf);
LocalFree(lpMsgBuf);
}
e->Delete();
return;
}
try {
Out.Write(cbBuffer,nSize);
}
catch(CFileException *e){
char *lpMsgBuf;
if(FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,e->m_lOsError,
MAKELANGID(LANG_NEUTRAL,
SUBLANG_DEFAULT),
(LPSTR)&lpMsgBuf,0,NULL)>0){
AfxMessageBox(lpMsgBuf);
LocalFree(lpMsgBuf);
}
e->Delete();
return;
}
nFilesize=nSize;
}
}
else
AfxMessageBox("不能打开"+Filename);
}
}
}
else
AfxMessageBox("不能创建输出文件");
 
CFile //创建/打开文件 CFile file; file.Open(_T("test.txt"),CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite); 文件打开模式可组合使用,用“|”隔开,常用的有以下几种: CFile::modeCreate:以新建方式打开,如果文件不存在,新建;如果文件已存在,把该文件长度置零,即清除文件原有内容。 CFile::modeNoTruncate:以追加方式打开,如果文件存在,打开并且不将文件长度置零,如果文件不存在,会抛出异常。一般与CFile::modeCreate一起使用,则文件不存在时,新建一个文件;存在就进行追加操作。 CFile::modeReadWrite:以读写方式打开文件。 CFile::modeRead:只读。 CFile::modeWrite:只写。 //写入数据 CString strValue = "Hello World!"; file.Write(strValue,strValue.GetLength()); //追加数据 file.SeekToEnd(); //将指针移至文件末尾进行追加 file.Write(strValue,strValue.GetLength()); //关闭文件 file.Close(); CStdioFile CStdioFile是CFile的派生类,对文件进行流式操作,对于文本文件的读写很有用处,可按行读取写入。 //写入数据 CString strValue = "Hello World!"; file.WriteString(strValue); //读取数据 CString strRead; file.ReadString(strRead); 当文件存在多行数据需要逐行读取时,可用函数BOOL CStdioFile::ReadString(CString& rString),当遇到"\n "时读取截断,如果文件未读完,返回true,否则返回false。 //逐行读取文件内容,存入strRead while(file.ReadString(strRead)) { ...; } 各种关于文件的操作在程序设计中是十分常见,如果能对其各种操作都了如指掌,就可以根据实际情况找到最佳的解决方案,从而在较短的时间内编写出高效的代码,因而熟练的掌握文件操作是十分重要的。本文将对Visual C++中有关文件操作进行全面的介绍,并对在文件操作中经常遇到的一些疑难问题进行详细的分析。   1.文件的查找   当对一个文件操作时,如果不知道该文件是否存在,就要首先进行查找。MFC中有一个专门用来进行文件查找的类CFileFind,使用它可以方便快捷地进行文件的查找。下面这段代码演示了这个类的最基本使用方法。   CString strFileTitle;   CFileFind finder;   BOOL bWorking = finder.FindFile("C:\\windows\\sysbkup\\*.cab");   while(bWorking)   {   bWorking=finder.FindNextFile();   strFileTitle=finder.GetFileTitle();   }   2.文件的打开/保存对话框   让用户选择文件进行打开和存储操作时,就要用到文件打开/保存对话框。MFC的类CFileDialog用于实现这种功能。使用CFileDialog声明一个对象时,第一个BOOL型参数用于指定文件的打开或保存,当为TRUE时将构造一个文件打开对话框,为FALSE时构造一个文件保存对话框。   在构造CFileDialog对象时,如果在参数中指定了OFN_ALLOWMULTISELECT风格,则在此对话框中可以进行多选操作。此时要重点注意为此CFileDialog对象的m_ofn.lpstrFile分配一块内存,用于存储多选操作所返回的所有文件路径名,如果不进行分配或分配的内存过小就会导致操作失败。下面这段程序演示了文件打开对话框的使用方法。   CFileDialog mFileDlg(TRUE,NULL,NULL,   OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT|OFN_ALLOWMULTISELECT,   "All Files (*.*)|*.*||",AfxGetMainWnd());   CString str(" ",10000);   mFileDlg.m_ofn.lpstrFile=str.GetBuffer(10000);   str.ReleaseBuffer();   POSITION mPos=mFileDlg.GetStartPosition();   CString pathName(" ",128);   CFileStatus status;   while(mPos!=NULL)   {   pathName=mFileDlg.GetNextPathName(mPos);   CFile::GetStatus( pathName, status );   }   3.文件的读写   文件的读写非常重要,下面将重点进行介绍。文件读写的最普通的方法是直接使用CFile进行,如文件的读写可以使用下面的方法:   //对文件进行读操作   char sRead[2];   CFile mFile(_T("user.txt"),CFile::modeRead);   if(mFile.GetLength()<2)   return;   mFile.Read(sRead,2);   mFile.Close();   //对文件进行写操作   CFile mFile(_T("user.txt "), CFile::modeWrite|CFile::modeCreate);   mFile.Write(sRead,2);   mFile.Flush();   mFile.Close();   虽然这种方法最为基本,但是它的使用繁琐,而且功能非常简单。我向你推荐的是使用CArchive,它的使用方法简单且功能十分强大。首先还是用CFile声明一个对象,然后用这个对象的指针做参数声明一个CArchive对象,你就可以非常方便地存储各种复杂的数据类型了。它的使用方法见下例。   //对文件进行写操作   CString strTemp;   CFile mFile;   mFile.Open("d:\\dd\\try.TRY",CFile::modeCreate|CFile::modeNoTruncate|CFile::modeWrite);   CArchive ar(&mFile,CArchive::store);   ar<>strTemp;   ar.Close();   mFile.Close();   CArchive的 <> 操作符用于简单数据类型的读写,对于CObject派生类的对象的存取要使用ReadObject()和WriteObject()。使用CArchive的ReadClass()和WriteClass()还可以进行类的读写,如:   //存储CAboutDlg类   ar.WriteClass(RUNTIME_CLASS(CAboutDlg));   //读取CAboutDlg类   CRuntimeClass* mRunClass=ar.ReadClass();   //使用CAboutDlg类   CObject* pObject=mRunClass->CreateObject();   ((CDialog* )pObject)->DoModal();   虽然VC提供的文档/视结构中的文档也可进行这些操作,但是不容易理解、使用和管理,因此虽然很多VC入门的书上花费大量篇幅讲述文档/视结构,但我建议你最好不要使用它的文档。关于如何进行文档/视的分离有很多书介绍,包括非常著名的《Visual C++ 技术内幕》。   如果你要进行的文件操作只是简单的读写整行的字符串,我建议你使用CStdioFile,用它来进行此类操作非常方便,如下例。   CStdioFile mFile;   CFileException mExcept;   mFile.Open( "d:\\temp\\aa.bat", CFile::modeWrite, &mExcept);   CString string="I am a string.";   mFile.WriteString(string);   mFile.Close();  4.临时文件的使用   正规软件经常用到临时文件,你经常可以会看到C:\Windows\Temp目录下有大量的扩展名为tmp的文件,这些就是程序运行是建立的临时文件。临时文件的使用方法基本与常规文件一样,只是文件名应该调用函数GetTempFileName()获得。它的第一个参数是建立此临时文件的路径,第二个参数是建立临时文件名的前缀,第四个参数用于得到建立的临时文件名。得到此临时文件名以后,你就可以用它来建立并操作文件了,如:   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.文件的复制、删除等   MFC中没有提供直接进行这些操作的功能,因而要使用SDK。SDK中的文件相关函数常用的有CopyFile()、CreateDirectory()、DeleteFile()、MoveFile()。它们的用法很简单,可参考MSDN。 1,判断文件是否存在 access(filename,mode); 2,对于不同用途又不同的文件操作,其中API函数CreateFile()也是比较有用处理方式,对于巨型文件很合适的其他的楼上的大都说了,不重复了. [1]显示对话框,取得文件名 CString FilePathName; CFileDialog dlg(TRUE);///TRUE为OPEN对话框,FALSE为S***E AS对话框 if (dlg.DoModal() == IDOK) FilePathName=dlg.GetPathName(); 相关信息:CFileDialog 用于取文件名的几个成员函数: 假如选择的文件是C:\WINDOWS\TEST.EXE 则(1)GetPathName();取文件名全称,包括完整路径。取回C:\WINDOWS\TEST.EXE (2)GetFileTitle();取文件全名:TEST.EXE (3)GetFileName();取回TEST (4)GetFileExt();取扩展名EXE [2]打开文件 CFile file("C:\HELLO.TXT",CFile::modeRead);//只读方式打开 //CFile::modeRead可改为 CFile::modeWrite(只写), //CFile::modeReadWrite(读写),CFile::modeCreate(新建) 例子: { CFile file; file.Open("C:\HELLO.TXT",CFile::modeCreate|Cfile::modeWrite); . . . } [3]移动文件指针 file.Seek(100,CFile::begin);///从文件头开始往下移动100字节 file.Seek(-50,CFile::end);///从文件末尾往上移动50字节 file.Seek(-30,CFile::current);///从当前位置往上移动30字节 file.SeekToBegin();///移到文件头 file.SeekToEnd();///移到文件尾 [4]读写文件 读文件: char buffer[1000]; file.Read(buffer,1000); 写文件: CString string("自强不息"); file.Write(string,8); [5]关闭文件 file.Close();
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值