2

This question is very similar to Loading a file into a vector; however, in this case, I want to load it into a vector of unsigned chars.

Using the code from the other question, what is the best way to load an unsigned char vector?

std::vector<char> vec;  // Would like this to be std::vector<unsigned char> vec;
std::ifstream file;
file.exceptions(
    std::ifstream::badbit
  | std::ifstream::failbit
  | std::ifstream::eofbit);
file.open("test.txt");
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));
}
Community
  • 1
  • 1
Macho Matt
  • 1,286
  • 4
  • 16
  • 32

1 Answers1

5

Change std::vector<char> vec; to std::vector<unsigned char> vec;

Andreas Brinck
  • 51,293
  • 14
  • 84
  • 114
  • I get the following compilation error when doing that: invalid conversion from 'unsigned char*' to 'std::basic_istream::char_type* {aka char*}' – Macho Matt Apr 17 '12 at 14:39
  • 4
    @MachoMatt Add a cast to the first argument of your call to the read function: `reinterpret_cast(&vec.front())` – Benjamin Lindley Apr 17 '12 at 14:44
  • Accepted with @benjamin-lindley's comment. Both the accepted answer and the comment are needed. – Macho Matt Apr 17 '12 at 14:54