几天以来,我在 Windows 共享驱动器 (Windows 10) 上创建简单的文本文件时遇到了不稳定的情况。 fstream文件随机打开失败
是否有人对可能的根本原因(防病毒软件、Windows 共享驱动器的已知问题……)以及如何获取有关文件创建失败原因的更多详细信息有想法。
const std::string filename = "file.txt";
const int waitDuration_ms = 200;
const int maxAttempts = 10;
unsigned int loop = 0;
boost::random::mt19937 rng(0);
boost::random::uniform_int_distribution<> waitBetweenLoops_ms(0, 1000);
while (true)
{
std::cout << "Loop " << loop << std::endl;
bool done = false;
int attempt = 0;
for (attempt = 0; attempt < maxAttempts; attempt++)
{
fstream oFile("file.txt", std::ofstream::out | std::ofstream::trunc);
if (!oFile.is_open())
{
std::cout << "Attempt to write " + filename + " failed" << std::endl;
Sleep(waitDuration_ms);
continue;
}
else
{
oFile << "Hello World" << std::endl;
oFile.close();
done = true;
break;
}
}
if (!done)
{
std::cout << "Failed to create file: " + filename + " after " + std::to_string(attempt) + " attempts" << std::endl;
FAIL();
}
const int waitNextLoop_ms = waitBetweenLoops_ms(rng);
std::cout << "Wait next loop (ms): " << waitNextLoop_ms << std::endl;
Sleep(waitNextLoop_ms);
loop++;
}