确定目录是否可写

Determine if directory is writeable

本文关键字:是否      更新时间:2023-10-16

我需要从c++程序中确定Linux文件系统上的目录是否可写。我最初的(天真的)解决方案是打开一个文件并尝试使用ofstream写入它,但是流不会抛出异常(除非你打开它们)。

这是我的第一个尝试。注意,在运行测试用例之前,/tmp/protectedstorage-test/mnt被挂载为只读):
class create_test_file_failed {};
void create_test_file() {
    std::ofstream os;
    os.open("/tmp/protectedstorage-test/mnt/test_file", std::ofstream::out | std::ofstream::trunc);
    if (os.fail())
        throw create_test_file_failed{};
    os << MAGIC_NUMBER;
    os.close();
}
bool not_writable_exception_check(std::exception const& ex) {
    return true;
}
BOOST_FIXTURE_TEST_CASE ( uninitialized_mirror_test ) {
    BOOST_CHECK_EXCEPTION(create_test_file, create_test_file_failed, not_writable_exception_check);
}

然而,os.fail()似乎总是返回false。我也尝试了os.bad(),但没有成功。

那么,这是我的第二次尝试:

void create_test_file() {
    std::ofstream os;
    os.exceptions(std::ofstream::failbit | std::ofstream::badbit);
    os.open("/tmp/protectedstorage-test/mnt/test_file", std::ofstream::out | std::ofstream::trunc);
    os << MAGIC_NUMBER;
    os.close();
}
bool not_writable_exception_check(std::exception const& ex) {
    return true;
}
BOOST_FIXTURE_TEST_CASE ( uninitialized_mirror_test ) {
    BOOST_CHECK_EXCEPTION(create_test_file, std::exception, not_writable_exception_check);
}

当我运行单元测试时,这会导致以下消息:

halfmirror_test.cpp(66): error in "uninitialized_mirror_test": exception std::exception is expected

如果我删除宏BOOST_CHECK_EXCEPTION并简单地调用该函数,我将得到以下消息,这意味着抛出了从std::exception派生的异常:

unknown location(0): fatal error in "uninitialized_mirror_test": std::exception: basic_ios::clear

由于basic_ios::clear是一个方法,而不是一个类型,似乎我应该捕捉std::exception

这是怎么回事?为什么fail()不能工作?抛出的是什么类型,这样我就可以验证它是否被抛出了?

我看到过其他的答案表明检查文件权限是实现这一点的最好方法,但是这些权限并不能真正告诉您关于只读文件系统的任何信息——在这种情况下,具有可写权限的文件确实没有。

stat是你的朋友。

stat, fstat, lstat - get file status 

如果您正在使用boost,请考虑boost::filesystem