确定目录是否可写
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
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 检查输入是否不是整数或数字
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 此代码是否违反一个定义规则
- 是否需要删除包含对象的"pair"?
- 是否可以从int转换为enum类类型
- 无论条件是否为true,if总是在c++中执行
- 如何找到大小'x'数组是否完全填充,在C++?
- 检查值是否在集合p1和p2中,但不在p3中
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- C/C++预处理器是否可以检测一些编译器选项
- 是否可以用"iostream"包装现有的TCP/OOpenSSL会话