<分区>
Possible Duplicate:
Efficient way of reading a file into an std::vector<char>?
这可能是一个简单的问题,但是我是 C++ 的新手,我无法弄清楚。我正在尝试加载一个二进制文件并将每个字节加载到一个 vector 中。这适用于小文件,但当我尝试读取大于 410 字节的文件时,程序崩溃并显示:
This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.
我在 Windows 上使用 code::blocks。
这是代码:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
std::vector<char> vec;
std::ifstream file;
file.exceptions(
std::ifstream::badbit
| std::ifstream::failbit
| std::ifstream::eofbit);
file.open("file.bin");
file.seekg(0, std::ios::end);
std::streampos length(file.tellg());
if (length) {
file.seekg(0, std::ios::beg);
vec.resize(static_cast<std::size_t>(length));
file.read(&vec.front(), static_cast<std::size_t>(length));
}
int firstChar = static_cast<unsigned char>(vec[0]);
cout << firstChar <<endl;
return 0;
}