开发者

How check if string specifies directory?

开发者 https://www.devze.com 2023-02-23 06:31 出处:网络
Suppose there is a some string: std::string some_string = \"some_string\"; And I want to know if chdir(some_string.c_str()) will return -1 or not without calling it. Is there quick way to do this?

Suppose there is a some string:

std::string some_string = "some_string";

And I want to know if chdir(some_string.c_str()) will return -1 or not without calling it. Is there quick way to do this?

P.S. I want my code to work als开发者_开发知识库o for windows, there I'm going to use _chdir()


#ifdef WIN32
# include <io.h>
#else
# include <unistd.h>
#endif

int access(const char *pathname, int mode);
// check user's permissions for a file

int mode values:

00 - Existence only, 02 - Write-only, 04 - Read-only, 06 - Read and write.

Function returns 0 if the file has the given mode.


I would use Boost's is_directory function, you can find more info on Boost's Filesystem Reference page.


I want to know if chdir(some_string.c_str()) will return -1 or not without calling it

You need to be careful about making those kinds of checks. The problem is if you rely on their result, because, in between you making the check and performing an operation that relies on the check, another process might have performed an operation (rmdir in this case) that invalidates the assumptin in your code. That is, you can introduce a race hazard into your code.


Since you want it to work for Windows, use GetFileAttributes() which returns File Attribute Constants.

GetFileAttributesEx is even better.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号