【发布时间】:2012-09-15 22:43:03
【问题描述】:
我编写了一个函数来测试文件夹的可读性/可写性。
为了对其进行单元测试,我需要生成不同的案例:
- 一个包含可读写文件的文件夹
- 包含可读文件(不可写)的文件夹
- 一个不可写也不可读的文件夹。
到此为止,这是我来的函数的代码:
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());
}
现在进行测试(通过 Google 测试完成):
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);
}
当我会更进一步时,我会为其他情况添加更多内容。
现在游戏已经开放,可以提出更好的解决方案:-)
【问题讨论】:
-
目录的执行位决定了你是否可以读/写里面的文件。目录的权限不能使文件中的文件可读或可写,只能同时或不能。此外,创建文件需要执行位和写入位。
-
正确的方法是读或写。如果你没有得到权限被拒绝的错误,那么你就成功了。否则,您将陷入竞争状态。
-
我刚刚找到了posix访问函数()。所以我有可读 = access(path.c_str(), R_OK) == 0;可写=访问(path.c_str(),W_OK)== 0;你怎么看?
-
通过访问,您打开了一个安全漏洞。在
man access中阅读更多信息(Notes 中的警告)
标签: c++ linux unit-testing