CreatePath - Full Path Creation (wstring version)

本文介绍了一个使用C++实现的递归函数,用于创建包含多个层级的路径。该函数能够处理尾随斜杠和网络位置,并通过调用SetLastError()来简化错误验证过程。

Environment: Visual C++

This is a simple function I wrote in order to deal with creating complete (multi-level) paths.

The function works recursively, and uses std::wstring , but can actaully work on any basic_string -based string. It can deal with trailing slashes (eg. "c:/temp/" vs. "c:/temp"), as well as network locations (eg. "//machine/shared").

You might notice the call to SetLastError() . The reason is to make it easy to verify what went wrong in case of an error - instead of handling exceptions and/or error strings, all you have to do is call GetLastError() if the function returns false .

You can use the function to make sure a directory exists before creating a file in it:

 

Here is the source code:

bool CreatePath(std::wstring &wsPath)
{
DWORD attr;
int pos;
bool result = true;

// Check for trailing slash:
pos = wsPath.find_last_of(SLASH);
if (wsPath.length() == pos + 1) // last character is "/"
{
wsPath.resize(pos);
}

// Look for existing object:
attr = GetFileAttributesW(wsPath.c_str());
if (0xFFFFFFFF == attr) // doesn't exist yet - create it!
{
pos = wsPath.find_last_of(SLASH);
if (0 < pos)
{
// Create parent dirs:
result = CreatePath(wsPath.substr(0, pos));
}
// Create node:
result = result && CreateDirectoryW(wsPath.c_str(), NULL);
}
else if (FILE_ATTRIBUTE_DIRECTORY != attr)
{ // object already exists, but is not a dir
SetLastError(ERROR_FILE_EXISTS);
result = false;
}

return result;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值