我创建了一个小型 RAII 类,它创建一个唯一的临时目录并在销毁时再次删除它。在 Linux 上,它使用 mkdtemp()
来实现此目的:
// temporaryDirectoryPath is an std::vector<char>
// containing u8"/tmp/nuclex-pixels-unittest-XXXXXX"
// Let mkdtemp() sort out a unique directory name for us (and create it!)
const char *directoryName = ::mkdtemp(&temporaryDirectoryPath[0]);
if(directoryName == nullptr) {
perror("mkdtemp() failed."); // DEBUGGING. REMOVE.
throw std::runtime_error("mkdtemp() failed.");
}
单独运行时效果很好:runnable code on ideone.com
但是,如果我在 GoogleTest 1.8.1 中使用相同的代码单元测试声明如下:
TEST(MyTestFixture, CanFlumbleTempDirectory) {
TemporaryDirectoryScope temporaryDirectory;
// Could call temporaryDirectory.GetPath() here...
}
失败:
Passing the following to mkdtemp(): /tmp/nuclex-pixels-unittest-XXXXXX
mkdtemp() failed.: Invalid argument
GoogleTest 如何干扰 mkdtemp()
?
最佳答案
您传递给 mkdtemp
的字符串不可靠地以 null 终止:
// Then append our directory name template to it
const char directoryNameTemplate[] = u8"nuclex-pixels-unittest-XXXXXX";
{
const char *iterator = directoryNameTemplate;
while(*iterator != 0) {
temporaryDirectoryPath.push_back(*iterator);
++iterator;
}
}
std::vector<char>
不执行隐式空终止,与 std::string
不同。如果"XXXXXX"
后面碰巧有一个空字节,那么这会偶然发生。后缀。是否是这种情况取决于执行环境。
关于c++ - 为什么在googletest中调用 `mkdtemp()`失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58680718/