MFC中没有提供直接进行这些操作的功能,因而要使用SDK。SDK中的文件相关函数常用的有
CopyFile()、CreateDirectory()、DeleteFile()、MoveFile()。它们的用法很简单,MSDN中给出:
BOOL WINAPI CopyFile(
_In_ LPCTSTR lpExistingFileName,//源文件名
_In_ LPCTSTR lpNewFileName,//目标文件名
_In_ BOOL bFailIfExists//if为TRUE,那么如果文件存在就会调用失败,否则就会改写文件
);
返回值:非零表示成功,零表示失败。有错误可以调用:GetLastError
BOOL WINAPI CreateDirectory(
_In_ LPCTSTR lpPathName,//要创建的文件名
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes//安全属性
);
使用:
CString str = “d:\\TEST”;
CreateDirectory(str, NULL);
str = str + “\\temp”;
CreateDirectory(str, NULL);
BOOL WINAPI DeleteFile(
_In_ LPCTSTR lpFileName//要删除的文件名
);
BOOL WINAPI MoveFile(
_In_ LPCTSTR lpExistingFileName,//已经存在的文件或者文件夹
_In_ LPCTSTR lpNewFileName//没有存在,要创建的文件或者文件名
);
OK,看完了这几个函数我们就来看一下完整的实例代码,但是文件操作不仅仅是这几个函数就能ok的,详细参见 MSDN
/
//MFC版 文件拷贝
/
void FileCopyTo(CString source, CString destination, CString searchStr, BOOL cover = TRUE)
{
CString strSourcePath = source;
CString strDesPath = destination;
CString strFileName = searchStr;
CFileFind filefinder;
CString strSearchPath = strSourcePath + "\\" + strFileName;
CString filename;
BOOL bfind = filefinder.FindFile(strSearchPath);
CString SourcePath, DisPath;
while (bfind)
{
bfind = filefinder.FindNextFile();
filename = filefinder.GetFileName();
SourcePath = strSourcePath + "\\" + filename;
DisPath = strDesPath + "\\" + filename;
CopyFile((LPCSTR)SourcePath, (LPCSTR)DisPath, cover);
}
filefinder.Close();
}
/
//C++版 文件拷贝
/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <io.h>
#include <windows.h>
void FileCopyTo(char *source, char *dis, char *searchChars, bool bcover /*= true*/)
{
struct _finddata_t ffblk;
char path[256], SourcePath[256], DisPath[256];
sprintf(path,"%s\\q_*",source);
long done = _findfirst(path,&ffblk);
int find=0;
while (find==0)
{
if(strcmp(ffblk.name, "q_"))
{
sprintf(SourcePath, "%s\\%s",source, ffblk.name);
sprintf(DisPath, "%s\\%s",dis, ffblk.name);
CopyFile(SourcePath, DisPath, bcover);
}
find=_findnext(done,&ffblk);
}
_findclose(done);
}
下面来看文件删除:
//删除文件夹目录(非空)
bool DeleteDirectory(char* sDirName)
{
CFileFind tempFind;
char sTempFileFind[200] ;
sprintf(sTempFileFind,"%s\\*.*",sDirName);
BOOL IsFinded = tempFind.FindFile(sTempFileFind);
while (IsFinded)
{
IsFinded = tempFind.FindNextFile();
if (!tempFind.IsDots())// 查看文件名是否是包含"."或"..",以表明它的确是一个目录
{
char sFoundFileName[200];
strcpy(sFoundFileName,tempFind.GetFileName().GetBuffer(200));
if (tempFind.IsDirectory())//文件是否是目录
{
char sTempDir[200];
sprintf(sTempDir,"%s\\%s",sDirName,sFoundFileName);
DeleteDirectory(sTempDir);
}
else
{
char sTempFileName[200];
sprintf(sTempFileName,"%s\\%s",sDirName,sFoundFileName);
DeleteFile(sTempFileName);
}
}
}
tempFind.Close();
if(!RemoveDirectory(sDirName))
{
return FALSE;
}
return TRUE;
}
我们来直接调用命令实现:
#include< stdlib.h >
#include< stdio.h >
int main( )
{
system( "md d:\\aa\\zhao " ); // 在下新建文件夹
system( "del d:\\aa\\zhao " ); // 删除该文件夹下的所有文件
}
2012/9/21
jofranks 于南昌