MFC文件操作大全
1.创建文件夹 CreateDirectory(%%1,NULL);
2.创建文件 CFile file;
file.Open(%%1,CFile::modeCreate|CFile::modeWrite);
3.删除文件 DeleteFile(%%1);
4.删除文件夹 RemoveDirectory(%%1);
5.删除一个目录下所有的文件夹 CFileFind finder; CString path; path.Format("%s\*.*",%%1); BOOL bWorking = finder.FindFile(path);
while (bWorking) { bWorking = finder.FindNextFile(); if (finder.IsDirectory()) { RemoveDirectory(finder.GetFilePath()); } }
6.清空文件夹 RemoveDirectory(%%1); CreateDirectory(%%1,NULL);
7.读取文件 char sRead[5120]; CFile mFile(_T(%%1),CFile::modeRead); while (sRead!=NULL) { mFile.Read(sRead,5120); CString %%2(sRead); %%3 } mFile.Close();
8.写入文件 CFile mFile(_T(%%1), CFile::modeWrite|CFile::modeCreate); mFile.Write(%%2,sizeof(%%2)); mFile.Flush(); mFile.Close();
10.读取文件属性 DWORD dwAttrs = GetFileAttributes(%%1); if(dwAttrs & FILE_ATTRIBUTE_READONLY) { %%2 } if(dwAttrs & FILE_ATTRIBUTE_NORMAL){ %%3 }
12.枚举一个目录下所有文件夹 CFileFind finder; CString path; path.Format("%s\*.*",%%1); BOOL bWorking = finder.FindFile(path);
while (bWorking) { bWorking = finder.FindNextFile(); if(finder.IsDirectory()){ CString %%1=finder.GetFilePath(); %%2 } }
-
7楼19.复制一个文件夹下所有的文件到另一个目录
//#include
using std::string;
char sep='/';
#ifdef _WIN32
sep='\';
#endif
CFileFind finder;
CString path;
path.Format("%s\*.*",%%1);
BOOL bWorking = finder.FindFile(path);
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);
//#include
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);
33.读取ini文件属性 CStdioFile inifile(%%1,CFile::modeRead); CString path = inifile.GetFilePath(); inifile.