1

可能重复:
将文件读入 std::vector<char> 的有效方法?

这可能是一个简单的问题,但是我是 C++ 新手,我无法弄清楚。我正在尝试加载二进制文件并将每个字节加载到向量中。这适用于一个小文件,但是当我尝试读取大于 410 字节时,程序崩溃并说:

此应用程序已请求运行时以不寻常的方式终止它。请联系应用程序的支持团队以获取更多信息。

我在 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;
}
4

1 回答 1

2

我不确定你的代码有什么问题,但我刚刚用这段代码回答了一个类似的问题。

读取字节为unsigned char

ifstream infile;

infile.open("filename", ios::binary);

if (infile.fail())
{
    //error
}

vector<unsigned char> bytes;

while (!infile.eof())
{
    unsigned char byte;

    infile >> byte;

    if (infile.fail())
    {
        //error
        break;
    }

    bytes.push_back(byte);
}

infile.close();
于 2012-10-13T20:40:03.637 回答