在 Windows 共享驱动器上以写模式打开 fstream 失败的可能根本原因

问题描述 投票:0回答:0

几天以来,我在 Windows 共享驱动器 (Windows 10) 上创建简单的文本文件时遇到了不稳定的情况。 fstream文件随机打开失败

  • 该文件显然是在我具有 W 权限的文件夹中创建的。
  • 下面代码创建的file.txt是由一个独特的应用程序创建的(没有实际共享这个文件) 该问题出现在 Windows 上。 下面是我运行以重现该问题的代码。它可能会运行几个小时然后失败。

是否有人对可能的根本原因(防病毒软件、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++;
}
c++ windows
© www.soinside.com 2019 - 2024. All rights reserved.