c++ - Determine if directory is writeable -


i need determine, within c++ program, whether directory on linux filesystem writeable or not. original (naive) solution open file , attempt write using ofstream, streams don't throw exceptions (unless turn them on).

here attempt #1. note /tmp/protectedstorage-test/mnt mounted read-only before running test case):

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); } 

however, os.fail() seems return false. tried os.bad() no success.

so, here second attempt:

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); } 

this results in following message when run unit test:

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

if remove macro boost_check_exception , call function, following message implying exception derived std::exception thrown:

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

since basic_ios::clear method, not type, seems should catching std::exception...

what's going on here? why isn't fail() working? type being thrown can verify it's being thrown?

i've seen other answers suggesting inspecting file permissions best way accomplish this, permissions don't tell on read-only filesystem - file writeable permissions isn't in case.

stat friend.

stat, fstat, lstat - file status  

if using boost, consider boost::filesystem


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -