I copy the bytes of a file into a vector of char
s. This works if the file is small, but if the file is too big, I get a heap-buffer overflow. I am trying to assert that the file size is less than a std::vector::max_size()
.
I have something a long the lines of:
#include <iostream>
#include <fstream>
#include <cassert>
#include <vector>
std::vector<char> read_file(const std::string& file_name) {
// Creats an ifstream object and opens the file given by the argument 'file_name'
// Opens in binary mode so that there are no misinterpretation of bytes
// std::ios::ate changes the seek pointer to the end of the file
std::ifstream input_file(file_name, std::ios::binary | std::ios::ate);
// Returns the seek pointer of the file
// The seek points to the end of the file because of 'std::ios::ate'
std::ifstream::pos_type position { input_file.tellg() };
// Checks to see if the file (lang: [file]) is too big
// I cannot compare successfully
assert(position >= byte_array.max_size());
// Create the vector we wish to return
// We need to cast so that the program compiles
std::vector<char> result ( static_cast<unsigned char>(position) );
// Change the seek pointer to the beginning
input_file.seekg(0, std::ios::beg);
// Am trying to copy all the bytes from from the the file into the
// vector named return
input_file.read(reinterpret_cast<char *>(result.data()), position);
return result;
}
int main() {
read_file("some_file.txt");
return 0;
}
As of now, the following line does not work:
assert(position >= byte_array.max_size());
How do I compare std::pos_type
(which is std::fpos
I think) and unsigned int
?