c++ - (C++) 将文件加载到 vector 中

标签 c++ file-io vector

<分区>

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

最佳答案

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

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

关于c++ - (C++) 将文件加载到 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12876760/

相关文章:

arrays - std::arrays 的 std::vector 的比较函数

c++ - 异常传播和 std::future

c++ - "overloaded member function not found"引用

c++ - 阶乘不适用于所有值

C++ 重复调用一个函数系统挂起

c++ - 从子类的STL vector 到基类 vector 的转换

c++ - Visual Studio .NET 2003 - 忽略 libcmt 与 libcmtd 的特定库

multithreading - 在 Spring Batch 作业中使用多线程步骤

c - 从文件中提取信息

file - 如何同时读取和写入二进制文件?