I wrote a function to check readability / writeability to a folder.
For unit testing, I need to create different cases:
- a folder with readable and writable files
- folder with readable files (not writable)
- A folder that cannot be written and cannot be read.
Here is the code for the function I came to, up to this point:
void FileUtils::checkPath(std::string path, bool &readable, bool &writable) { namespace bf = boost::filesystem; std::string filePath = path + "/test.txt"; // remove a possibly existing test file remove(filePath.c_str()); // check that the path exists if(!bf::is_directory(path)) { readable = writable = false; return; } // try to write in the location std::ofstream outfile (filePath.c_str()); outfile << "I can write!" << std::endl; outfile.close(); if(!outfile.fail() && !outfile.bad()) { writable = true; } // look for a file to read std::ifstream::pos_type size; char * memblock; for (bf::recursive_directory_iterator it(path); it != bf::recursive_directory_iterator(); ++it) { if (!is_directory(*it)) { std::string sFilePath = it->path().string(); std::ifstream file(sFilePath.c_str(), std::ios::in|std::ios::binary|std::ios::ate); if (file.is_open()) { size = file.tellg(); if(size > 0) { memblock = new char [1]; file.seekg (0, std::ios::beg); file.read (memblock, 1); file.close(); delete[] memblock; if(!file.fail() && !file.bad()) { readable = true; } break; } } else { // there is a non readable file in the folder // readable = false; break; } } } // delete the test file remove(filePath.c_str()); }
Now with tests (with Google tests):
TEST_F(FileUtilsTest, shouldCheckPath) { // given an existing folder namespace fs = boost::filesystem; fs::create_directory("/tmp/to_be_deleted"); bool readable = false, writable = false; FileUtils::checkPath("/tmp/to_be_deleted",readable, writable); fs::boost::filesystem::remove_all("/tmp/to_be_deleted"); EXPECT_TRUE(readable && writable); }
I will add more for other occasions when I go further.
Now the game is open to offer the best solution :-)
source share