首页 > 解决方案 > 读取文件时运行时的未知行为

问题描述

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

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

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

我的代码有问题吗?


编辑

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

标签: c++readfile

解决方案


你在读书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";
    }
}

推荐阅读