创建目录利用_mkdir
,删除目录利用_rmdir
目录是否可以访问_access
设置当前的访问目录_chdir
利用_findfirst,_findnext进行遍历整个目录,遍历结束需要关闭句柄_findclose。
- #include <io.h>
- #include <windows.h>
- #include <direct.h>
- #include <sys/stat.h>
- #include <string.h>
- #include <stdio.h>
- bool createDirectory(const char* pathName)
- {
- char path[MAX_PATH];
- memset(path, 0x00, MAX_PATH);
- const char* pos = pathName;
- while ((pos = strchr(pos, '\\')) != NULL)
- {
- memcpy(path, pathName, pos - pathName + 1);
- pos++;
- if (_access(path, 0) == 0)
- {
- continue;
- }
- else
- {
- int ret = _mkdir(path);
- if (ret == -1)
- {
- return false;
- }
- }
- }
- return true;
- }
- bool deleteDirectory( char* pathName)
- {
- struct _finddata_t fData;
- memset(&fData, 0, sizeof(fData));
- if (_chdir(pathName) != 0) //_chdir函数设置当前目录
- {
- printf("chdir failed: %s\n",pathName);
- return false;
- }
- intptr_t hFile = _findfirst("*",&fData); //参数1:char *类型,"*"表示通配符,可以查找文件、文件夹
- if(hFile == -1)
- {
- printf("_findfirst error!\n");
- return false;
- }
- do
- {
- if(fData.name[0] == '.')
- continue;
- if(fData.attrib == _A_SUBDIR) //子文件夹
- {
- char dirPath[MAX_PATH];
- memset(dirPath,0,sizeof(pathName));
- strcpy_s(dirPath,pathName);
- strcat_s(dirPath,"\\");
- strcat_s(dirPath,fData.name);
- deleteDirectory(dirPath); //recursion subdir
- printf("remove dir: %s\n",dirPath);
- _chdir("..");
- _rmdir(dirPath);
- }
- else
- {
- char filePath[MAX_PATH];
- memset(filePath,0,sizeof(filePath));
- strcpy_s(filePath,pathName);
- strcat_s(filePath,"\\");
- strcat_s(filePath,fData.name);
- remove(filePath);
- printf("remove file: %s\n",filePath);
- }
- }while(_findnext(hFile,&fData) == 0);
- _findclose(hFile); //close
- return true;
- }
- int main(void)
- {
- createDirectory("D:\\test\\txt");
- deleteDirectory("D:\\test");
- return 0;
- }