【问题标题】:Unknown behavior at runtime when reading a file读取文件时运行时的未知行为
【发布时间】:2020-07-07 22:58:18
【问题描述】:

我有以下简单的代码来读取文件:

std::basic_ifstream<wchar_t> RFile(L"C:\\file.exe", std::ios::binary|std::ios::ate);
if (!RFile.is_open()){ cout << "Cannot open the file." << endl; return 0;}
std::streamoff fileSize = RFile.tellg();
wstring fileContent;
fileContent.reserve(fileSize);
RFile.seekg(0, std::ios::beg);
if (!RFile.read(&fileContent[0], fileSize)) cout << "An error when reading the file." << endl;
RFile.close();

编译或运行时也没有出现错误,但运行时/调试时出现未知行为,程序没有结束并仍在等待(类似于等待输入)。

我的代码有问题吗?


编辑

程序终于结束并完成了它的工作,但是,我注意到:

  • 该程序需要将近 32 秒才能读取 17 MB,这是正常的还是我的代码中有某些东西(我认为这很慢)?
  • 另外,当使用char 数据类型而不是wchar_t 时,读取过程变得应有的快,那么,wchar_t 数据类型的问题还是什么?

【问题讨论】:

  • 无关:在if (!RFile.is_open()) cout &lt;&lt; "Cannot open the file." &lt;&lt; endl; 之后,您可能不应该让程序继续运行,就像文件已打开一样。
  • 它在哪里等着呢?你的调试器说什么?什么是调用堆栈?
  • 调试程序时,它在哪里停止等待?通常通过检查锁定地点可以获得很好的情报。
  • tellg 是否会给你wchar_ts 中的文件大小、旧字节或其他内容?了解这一点很重要。
  • 可能不相关,但我认为您想要fileContent.resize(fileSize) 而不是fileContent.reserve(fileSize)

标签: c++ readfile


【解决方案1】:

您正在阅读wstring。您系统上wchar_t 的大小可能不是一个字节。以字节为单位的文件大小是不正确的。

我会使用更惯用的方法,而不是做手工作业:

#include <fstream>
#include <string>
#include <iostream>

int main() {
    std::wifstream file;
    try {
        file.exceptions(std::ios::failbit | std::ios::badbit);
        file.open("C:\\file.exe", std::ios::binary);

        std::wstring const content(
                std::istreambuf_iterator<wchar_t>(file), {});

        std::cout << "Read " << content.size() << " characters\n";
    } catch(std::exception const& e) {
        std::wcout << "error reading file: " << e.what() << "\n";
    }
}

【讨论】:

  • 您是否有理由相信非char 流的获取光标位置在某种程度上是“不正确的”?您能否提供有关此现象的更多信息?
  • 嗯。就 wchar_t 单位而言,可能是 tellg() should be correct。但是,我确实知道我不需要知道,而且我发现此代码的唯一其他地方具有讽刺意味的是另一个 had trouble with it 的人。我不确定我是否愿意花更多时间来了解更多信息,因为详细信息也会因平台而异。
猜你喜欢
  • 2017-08-31
  • 1970-01-01
  • 2015-06-05
  • 1970-01-01
  • 2021-09-14
  • 2015-04-09
  • 2019-03-07
  • 1970-01-01
  • 2017-03-26
相关资源
最近更新 更多