创建_中间/多级/嵌套_目录/文件夹 (Visual C++ 源代码)| Create intermediate directory (Visual C++ source code)

最近有个项目:用语音卡对呼叫中心中的话务录音。
录音文件保存在硬盘上,存放路径的格式大致如下:

录音文件根目录/接入号码/日期/xxxxxxxxxxxxxx.wav

比如:

D:/Record/186025/20060427/1_13600001111.wav
D:/Record/186050/20060428/45_13600002222.wav


语音卡提供了开发包,在录音时需要提供一个文件的 Handle,该文件也是通过开发包中
的 dx_fileopen 函数来 创建/打开的,当目录不存在时,dx_fileopen 函数并不自动
创建该目录,所以需要由自己的程序来“关照”……

在试图用 Win32 SDK 中的 CreateDirectory 函数创建文件夹时发现根本创建不了,
查阅 MSDN 得知 CreateDirectory 时必须确保上一级目录必须存在,
否则创建会失败,且 GetLastError() 返回 ERROR_PATH_NOT_FOUND 错误。

MSDN 当然也给出说明:可以用 SHCreateDirectoryEx 来创建多级目录,
然而使用 SHxxx 函数需要额外链接 shell32.lib 库,而且还得 #include <shlobj.h>,
这个我不大喜欢,于是乎自己写了个函数,凑合着能用。



/*
描述:
	创建多级目录
参数:
	strDirectory	要创建的目录,比如 D:/Folder1/Folder2 或者 Folder1/Folder2/Folder3
返回值:
	true	创建成功 或 目录已存在
	false	创建失败
*/
bool CreateIntermediateDirectory (const char *strDirectory)
{
	if (strDirectory==NULL || strDirectory[0]==0)
	{
		return false;
	}

	bool bErrorOccur = false;
	CString csDirectory = strDirectory;
	CString csIntermediateDirectory;

	csDirectory.Replace ('/', '//');
	while (csDirectory.Replace ("", "//") > 0);
	csDirectory.TrimRight ('//');

	int iLastIndex = 0;
	while (true)
	{
		iLastIndex = csDirectory.Find ('//', iLastIndex);

		if (iLastIndex == -1)
		{
			csIntermediateDirectory = csDirectory;
		}
		else
		{
			csIntermediateDirectory = csDirectory.Left (iLastIndex);
			iLastIndex ++;
		}

		// 如果该文件夹不存在,则创建之
		HANDLE hDirectory = 
		CreateFile (
			csIntermediateDirectory,
			GENERIC_READ,
			FILE_SHARE_READ,
			NULL,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS ,
			NULL
			);

		if (hDirectory == INVALID_HANDLE_VALUE)
		{
			BOOL bCreated = CreateDirectory (csIntermediateDirectory, NULL);
			if (!bCreated)
			{
				//logger.Log (LL_ERROR, "Create directory %s error! ErrorCode=%d",
				//	csIntermediateDirectory,
				//	GetLastError ()
				//	);
				bErrorOccur = true;
				break;
			}
		}
		else {
			CloseHandle (hDirectory);
		}

		if (iLastIndex == -1)
		{
			break;
		}
	}

	return !bErrorOccur;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值