c++visual-studiouwpofstreamwofstream

wofstream only creates an empty file c++


I have a for loop (below) that should output several strings to several files using wofstream. Unfortunately, it creates the file but does not output the string to the file. The files are always empty. I've looked through a lot of similar questions with no luck. Any help would be greatly appreciated. I'm on a Windows 10 machine using Visual Studio 2015 to write a UWP app.

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();
}

Solution

  • std::wofstream outFile(convertedPlatformPathandFilename);
    

    This creates a new file, and opens it for writing.

    outFile.open(convertedPlatformPathandFilename);
    

    This attempts to open the same file stream for writing a second time. Because the file stream is already open, this is an error. The error sets the stream into a failed state, and all attempts to write to the stream will now fail.

    This is how you end up with an empty output file. It gets created, and a duplicate, second attempt to open the same file stream object puts it into error state.