C++文件和目录的创建和删除

在创建之前检查文件或文件夹是否存在

 1 int  MyDiaLog::CheckDir(char strs[MAX_PATH])
 2 {
 3     FILE* fp=NULL;
 4     fp=fopen(strs,"r");
 6     if(!fp)
 7     {
 8         return -1;
 9     }else{
10         fclose(fp);
11         return 1;
12     }
13 }

创建目录,如果目录存在,删除目录。

使用PathIsDirectory验证目录是否存在

1 if (PathIsDirectory(Dir))
2 {
3     MyDiaLog::DeleteDirectory(Dir);
4 }
5 ::CreateDirectory(Dir,NULL);

使用递归的方法删除目录下的子目录和文件后删除目录

 1 void  MyDiaLog::DeleteDirectory(char* strDirName)
 2 {
 3     CFileFind tempFind;
 4     char strTempFileFind[MAX_PATH];
 5     sprintf(strTempFileFind,"%s\*.*", strDirName);
 6     BOOL IsFinded = tempFind.FindFile(strTempFileFind);
 7     while (IsFinded)
 8     {
 9         IsFinded = tempFind.FindNextFile();
10         if (!tempFind.IsDots()) 
11         {
12             char strFoundFileName[MAX_PATH];
13             strcpy(strFoundFileName, tempFind.GetFileName().GetBuffer(MAX_PATH));
14             if (tempFind.IsDirectory())
15             {
16                 char strTempDir[MAX_PATH];
17                 sprintf(strTempDir,"%s\%s", strDirName, strFoundFileName);
18                 DeleteDirectory(strTempDir);
19                 
20             }
21             else
22             {
23                 char strTempFileName[MAX_PATH];
24                 sprintf(strTempFileName,"%s\%s", strDirName, strFoundFileName);
25                 DeleteFile(strTempFileName);
26             }
27         }
28     }
29     RemoveDirectory(strDirName);
30     tempFind.Close();
31 
32 }

复制文件使用::CopyFile(SourceFile, NewFile, FALSE);

原文地址:https://www.cnblogs.com/kire/p/4505643.html