今天試著寫了一個創建多級目錄的函數,用C語言實現。
涉及的庫函數如下:
strcpy
strchr
_access
_mkdir
這些函數的具體使用方法參考msdn :),這里不再一一列出。
今天(20090623)有做了點更改,支持網絡路徑的創建。當然要先保證能對網絡目錄具有讀寫權限才可以:)
// 頭文件
#include <io.h>
#include <direct.h>
//==================================================================
//函數名: CreateMultiLevelDirectory
//作者: xinxin
//日期: 2009-06-21
//功能: 創建多級目錄
//輸入參數:保存多級目錄的字符串
//返回值: TRUE:創建成功; FALSE:失敗.
//==================================================================
BOOL CreateMultiLevelDirectory(const char *strFilePathName)
{
char strFilePath[260];
char strTemp[260];
char *s, *p;
strcpy(strFilePath, strFilePathName);
s = strFilePath;
// if strFilePathName is network path, skip the ip address/host name
// Modified on 20090623
if(0 == strncmp(s, "\\\\", 2))
{
s += 2;
s = strchr(s, '\\');
if(!s)
{
return (FALSE);
}
else
{
s += 1;
}
}
do
{
p = strchr(s, '\\');
if(p)
{
*p = '\0';
}
s = strFilePath;
// directory doesn't exist
if(-1 == _access(s, 0))
{
// failed to create directory.
if(-1 == _mkdir(s))
{
return (FALSE);
}
}
if(p)
{
*p = '\\';
s = p + 1;
}
} while(p);
return (TRUE);
}