Windows程序开发中我们经常会遇到下面的问题:
1.我们程序需要校验路径的合法性,但是Windows中没有直接能校验路径的合法性的函数。
2.我们需要创建多级目录,但是Windows中对于路径的创建函数
BOOL CreateDirectory(
LPCTSTR lpPathName, // directory name
LPSECURITY_ATTRIBUTES lpSecurityAttributes // SD
);
只能创建一层目录,没法直接创建多级目录。
3.我们删除路径,但是Windows中对于路径删除函数
BOOL RemoveDirectory(
LPCTSTR lpPathName // directory name
);
只能删除存在的空目录。(目录中没有任何文件及文件夹)。
针对上面的问题,自己实现了三个函数:
1)路径合法性校验函数:
// 说明: 检查路径的合法性
// 参数:
// strPath 绝对路径(以'\'结尾)
// arrayPath 用字符‘\’切割的字符数组
// 返回值:
// true 成功
// false 失败
bool CDirCreateAndDeleteDlg::IsValidPathAndSplitPath(const CString& strPath, CStringArray& arrayPath)
{
//判断路径长度是否合法
if(strPath.GetLength()<3||strPath.GetLength()>255){
return false;
}
//判断第一个字符是否为字母
if(strPath.GetAt(0)<'A'||strPath.GetAt(0)>'z'){
return false;
}
//判断第二字符是否为":"
if(strPath.GetAt(1) != ':'){
return false;
}
//判断第三个字符是否为"\"
if(strPath.GetAt(2) != '\\'){
return false;
}
//判断最后一个字符是否为"\"
if(strPath.GetAt(strPath.GetLength()-1) != '\\'){
return false;
}
//向字符数组中添加根目录,如:“C:\,D:\,...”
arrayPath.Add(strPath.Left(3));
//第一个字符‘\’之后的位置
int nPosStart = 3;
int nPosEnd = strPath.Find('\\', nPosStart);
while(nPosEnd != -1){
//从路径中提取"\"分割的字符(包含'\')
CString path = strPath.Mid(nPosStart, nPosEnd-nPosStart+1);
//判断是否有非法字符
if(path.FindOneOf(_T("/:*?\"<>|")) != -1){
return false;
}
//判断字符串path是否仅为‘\’
if(path.GetLength() == 1){
return false;
}
//将合法字符添加到字符数组中
arrayPath.Add(path);
//继续下个一个字符查找。
nPosStart = nPosEnd+1;
nPosEnd = strPath.Find('\\', nPosStart);
}
return true;
}
2)多级目录创建函数:
// 说明:创建全路径
// 参数:
// strPath 绝对路径(以'\'结尾)
// 返回值:
// 0x00 创建成功
// 0x01 创建失败
// 0x02 路径不合法
byte CDirCreateAndDeleteDlg::CreateAllDirectory(const CString& strPath)
{
CStringArray arrayPath;
if(!IsValidPathAndSplitPath(strPath, arrayPath)){
return 0x02;
}
CString strItem = _T("");
for(int i = 0; i < arrayPath.GetCount(); i++){
strItem += arrayPath.GetAt(i);
//判断该路径是否存在
if(GetFileAttributes(strItem) != INVALID_FILE_ATTRIBUTES){
continue;
}
if(!CreateDirectory(strItem, NULL)){
return 0x01;
}
}
return 0x00;
}
3)删除存在目录下的所有文件和文件夹:
// 说明:删除路径下面所有的文件和文件夹
// 参数:
// strPath 绝对路径(以'\'结尾)
// 返回值:
// 0x00 删除成功
// 0x01 删除失败
// 0x02 路径不合法
byte CDirCreateAndDeleteDlg::DeleteAll(const CString& strPath)
{
CStringArray arrayPath;
//判断路径的合法性
if(!IsValidPathAndSplitPath(strPath, arrayPath)){
return 0x02;
}
CFileFind finder;
//判断路径存在
BOOL bIsFinded = finder.FindFile(strPath+_T("*.*"));
while(bIsFinded){
//查找路径下面的文件
bIsFinded = finder.FindNextFile();
//判断是'.'或者'..'
if(finder.IsDots()){
//忽略
continue;
}
//判断是路径
if(finder.IsDirectory()){
//如果是路径,继续迭代
byte byRet = DeleteAll(strPath+finder.GetFileName()+_T("\\"));
if(byRet != 0x00){
return byRet;
}
}
else{
//如果是文件,直接删除
if(!DeleteFile(strPath+finder.GetFileName())){
return 0x01;
}
}
}
//关闭finder搜索
finder.Close();
//删除空路径
return !RemoveDirectory(strPath);
}