c++ - 读取文件时运行时的未知行为
问题描述
我有以下简单的代码来读取文件:
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
数据类型的问题还是什么?
解决方案
你在读书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";
}
}
推荐阅读
- twilio - 如何在 Twilio WhatsApp 中发送带有文件名的 PDF 文件?
- c# - Unity3D firebase AUTH 不适用于 ANDROID
- java - 如何从外部 .class 文件中获取所有测试方法的名称
- java - 如何从查询中获得结果?(Java、SQL)
- flutter - “IconData”类型不是“Widget”类型的子类型
- operating-system - 访问 ChromeOS 上的系统级功能
- python - 在所有列表中查找列表列表的最小值
- c++ - VS C++ 重载作为临时对象引用的函数
- tensorflow - 具有向量输入和向量输出的 DQN 代理
- python - 在 DAG 中添加标签