【问题标题】:wofstream only creates an empty file c++wofstream 只创建一个空文件 c++
【发布时间】:2016-07-15 22:43:32
【问题描述】:

我有一个 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();
}

【问题讨论】:

  • 你试过outFile &lt;&lt; "Hello World";只是为了检查发生了什么?
  • 旁白:你为什么要构造一个字符串并将字符串写入outFile,而不是仅仅写入outFile?
  • 另外,您通过什么方式确定文件为空?我见过几次这样做是错误的。
  • 请发布MCVE,这样人们就不必猜测vctSchedulesToReturn 中的实际内容。
  • 赫尔基尔感谢您的帮助。字符串构造只是我故障排除的产物,但我不认为它会伤害任何东西,所以我就这样离开了。

标签: c++ visual-studio uwp ofstream wofstream


【解决方案1】:
std::wofstream outFile(convertedPlatformPathandFilename);

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

outFile.open(convertedPlatformPathandFilename);

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

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

【讨论】:

  • 就是这样。你只是为我节省了几个小时的挫败感。非常感谢!
  • @user2757835:这就是为什么在执行 I/O 时应该添加错误检查代码的一个很好的理由!
  • 赫尔基尔,感谢您的建议。正如您可能知道的那样,我对任何类型的实质性软件开发都很陌生。我很感激指导。我将添加一些错误检查。
猜你喜欢
  • 2018-02-09
  • 2010-10-22
  • 1970-01-01
  • 2014-06-17
  • 1970-01-01
  • 2013-11-30
  • 1970-01-01
  • 2011-11-10
  • 2015-06-29
相关资源
最近更新 更多