65.9K
CodeProject 正在变化。 阅读更多。
Home

文件夹实用工具:创建路径、删除文件夹、删除所有文件

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.54/5 (22投票s)

2005年6月6日

viewsIcon

115638

downloadIcon

1760

CreateDir 函数创建文件夹和子文件夹,从而完成整个路径。该函数克服了 CreateDirectory Win32 API 的限制。

引言

CreateDir 函数创建文件夹和子文件夹,从而完成传递给它的整个路径。如果文件夹已经存在,则保持不变,如果不存在,则创建它。CreateDirectory WIN32 API 允许我们创建一个目录,但它仅在父目录已经存在时才有效。该函数克服了此限制。

void CreateDir(char* Path)
{
 char DirName[256];
 char* p = Path;
 char* q = DirName; 
 while(*p)
 {
   if (('\\' == *p) || ('/' == *p))
   {
     if (':' != *(p-1))
     {
        CreateDirectory(DirName, NULL);
     }
   }
   *q++ = *p++;
   *q = '\0';
 }
 CreateDirectory(DirName, NULL);
}

DeleteAllFiles 函数删除指定路径中存在的所有文件(不包括文件夹)。

void DeleteAllFiles(char* folderPath)
{
 char fileFound[256];
 WIN32_FIND_DATA info;
 HANDLE hp; 
 sprintf(fileFound, "%s\\*.*", folderPath);
 hp = FindFirstFile(fileFound, &info);
 do
    {
       sprintf(fileFound,"%s\\%s", folderPath, info.cFileName);
       DeleteFile(fileFound);
 
    }while(FindNextFile(hp, &info)); 
 FindClose(hp);
}

EmptyDirectory 函数删除指定目录中的所有内容。RemoveDirectory WIN32 API 删除现有的空目录,但如果目录不为空,则不起作用。该函数克服了此限制。

void EmptyDirectory(char* folderPath)
{
 char fileFound[256];
 WIN32_FIND_DATA info;
 HANDLE hp; 
 sprintf(fileFound, "%s\\*.*", folderPath);
 hp = FindFirstFile(fileFound, &info);
 do
    {
        if (!((strcmp(info.cFileName, ".")==0)||
              (strcmp(info.cFileName, "..")==0)))
        {
          if((info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)==
                                     FILE_ATTRIBUTE_DIRECTORY)
          {
              string subFolder = folderPath;
              subFolder.append("\\");
              subFolder.append(info.cFileName);
              EmptyDirectory((char*)subFolder.c_str());
              RemoveDirectory(subFolder.c_str());
          }
          else
          {
              sprintf(fileFound,"%s\\%s", folderPath, info.cFileName);
              BOOL retVal = DeleteFile(fileFound);
          }
        }
 
    }while(FindNextFile(hp, &info)); 
 FindClose(hp);
}
© . All rights reserved.