最近有个项目:用语音卡对呼叫中心中的话务录音。 录音文件保存在硬盘上,存放路径的格式大致如下:录音文件根目录/接入号码/日期/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; }
创建_中间/多级/嵌套_目录/文件夹 (Visual C++ 源代码)| Create intermediate directory (Visual C++ source code)
最新推荐文章于 2024-04-30 22:35:34 发布