(C++)将文件加载到矢量中

(C++) Loading a file into a vector

本文关键字:加载 文件 C++      更新时间:2023-10-16

可能的重复项:
将文件读取到 std::vector 中的有效方法?

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

此应用程序已请求运行时在 不寻常的方式。请联系应用程序的支持团队了解更多信息 信息。

我正在窗口上使用代码::块。

这是代码:

#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;
}

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

读取字节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();