Visual Studio - Wofstream 只创建一个空文件 C++

visual studio - wofstream only creates an empty file c++

本文关键字:一个 C++ 文件 Studio Wofstream 创建 Visual      更新时间:2023-10-16

我有一个 for 循环(如下),它应该使用 wofstream 将多个字符串输出到多个文件中。不幸的是,它会创建文件,但不会将字符串输出到文件中。文件始终为空。我看过很多类似的问题,但没有运气。任何帮助将不胜感激。我在一台使用 Visual Studio 2015 的 Windows 10 机器上编写 UWP 应用程序。

for (size_t k=0;k < vctSchedulesToReturn.size();k++)
{
    auto platformPath = Windows::Storage::ApplicationData::Current->RoamingFolder->Path;
    std::wstring wstrplatformPath = platformPath->Data();
    std::wstring wstrPlatformPathAndFilename = wstrplatformPath + L"\" + availabilityData.month + L"_" + std::to_wstring(availabilityData.year) + L"_" + std::to_wstring(k) + L"_" + L"AlertScheduleOut.csv";
    std::string convertedPlatformPathandFilename(wstrPlatformPathAndFilename.begin(), wstrPlatformPathAndFilename.end());
    std::wofstream outFile(convertedPlatformPathandFilename);
    outFile.open(convertedPlatformPathandFilename);
    std::vector<std::pair<wstring, wstring>>::iterator pairItr;
    std::wstring strScheduleOutputString = L"";
    for (pairItr = vctSchedulesToReturn[k].second.begin(); pairItr!=vctSchedulesToReturn[k].second.end(); pairItr++)
    {
        strScheduleOutputString += pairItr->first + L",";
    }
    strScheduleOutputString += L"rn";
    for (pairItr = vctSchedulesToReturn[k].second.begin(); pairItr != vctSchedulesToReturn[k].second.end(); pairItr++)
    {
        strScheduleOutputString += pairItr->second + L",";
    }
    outFile << strScheduleOutputString;
    outFile.flush();
    outFile.close();
}
std::wofstream outFile(convertedPlatformPathandFilename);

这将创建一个新文件,并打开它进行写入。

outFile.open(convertedPlatformPathandFilename);

这将尝试打开同一文件流进行第二次写入。由于文件流已打开,因此这是一个错误。该错误将流设置为失败状态,现在所有写入流的尝试都将失败。

这就是您最终得到空输出文件的方式。它被创建,并且重复的第二次尝试打开相同的文件流对象会将其置于错误状态。