1

Possible Duplicate:
Efficient way of reading a file into an std::vector<char>?

This is probably a simple question, however I am new to C++ and I cannot figure this out. I am trying to load a binary file and load each byte to a vector. This works fine with a small file, but when I try to read larger than 410 bytes the program crashes and says:

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information.

I am using code::blocks on windows.

This is the code:

#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;
}
Community
  • 1
  • 1
Alden
  • 2,229
  • 1
  • 15
  • 21
  • 1
    This has already been asked. http://stackoverflow.com/questions/4761529/efficient-way-of-reading-a-file-into-an-stdvectorchar – andre Oct 13 '12 at 20:39
  • BTW, if the file is empty, and therefore you don't resize the vector, being empty, this `static_cast(vec[0])` would crash your app. – Marius Bancila Oct 13 '12 at 21:40
  • I think the catch is that you should open the file with `ios::binary`, which you don't specify. – Marius Bancila Oct 13 '12 at 21:41

1 Answers1

2

I'm not sure what's wrong with your code, but I just answered a similar question with this code.

Read the bytes as 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();
Geoff Montee
  • 2,587
  • 13
  • 14