1

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

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"\r\n";
    for (pairItr = vctSchedulesToReturn[k].second.begin(); pairItr != vctSchedulesToReturn[k].second.end(); pairItr++)
    {
        strScheduleOutputString += pairItr->second + L",";
    }
    outFile << strScheduleOutputString;
    outFile.flush();
    outFile.close();
}
4

1 回答 1

3
std::wofstream outFile(convertedPlatformPathandFilename);

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

outFile.open(convertedPlatformPathandFilename);

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

这就是你最终得到一个空输出文件的方式。它被创建,并且重复的第二次尝试打开相同的文件流对象使其进入错误状态。

于 2016-07-16T00:12:39.977 回答