如何检查字符串是否指定目录

How check if string specifies directory?

本文关键字:是否 字符串 何检查 检查      更新时间:2023-10-16

假设有一个字符串:

std::string some_string = "some_string";

我想知道chdir(some_string.c_str())是否会在不调用它的情况下返回-1。有快速的方法吗?

附言:我希望我的代码也适用于windows,在那里我将使用_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模式值:

00-仅存在,02-只写,04-只读,06-读写。

如果文件具有给定的模式,则函数返回0。

我会使用Boost的is_directory函数,您可以在Boost的Filesystem Reference页面上找到更多信息。

我想知道chdir(some_string.c_str())是否会在不调用的情况下返回-1

你在做这些检查时需要小心。问题是,如果你依赖于它们的结果,因为在你进行检查和执行依赖于检查的操作之间,另一个进程可能执行了一个操作(在这种情况下是rmdir(,该操作会使代码中的假设无效。也就是说,您可以在代码中引入种族风险。

由于希望它适用于Windows,请使用返回File Attribute ConstantsGetFileAttributes()

CCD_ 7甚至更好。