Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector<unsigned char> remains empty after reading binary file using std::ifstream

This is my first question on StackOverflow so I apologize in advance if there is anything I am missing in my question or some rule I didn't follow. Please edit my question or tell me in the comments how I should improve my question, thank you.

I am trying to read a binary file into a std::vector<unsigned char> in C++ using std::ifstream. The problem is that it appears the file was read successfully, but the vector remains empty.

Here is the function that I used for reading the file:

void readFile(const std::string &fileName, std::vector<unsigned char> &fileContent)
{
    std::ifstream in(fileName, std::ifstream::binary);

    // reserve capacity
    in.seekg(0, std::ios::end);
    fileContent.reserve(in.tellg());
    in.clear();
    in.seekg(0, std::ios::beg);

    // read into vector
    in.read(reinterpret_cast<char *>(fileContent.data()), fileContent.capacity());

    if(in)
        std::cout << "all content read successfully: " << in.gcount() << std::endl;
    else
        std::cout << "error: only " << in.gcount() << " could be read" << std::endl;

    in.close();
}

And this is how I called the function in main():

std::vector<unsigned char> buf;
readFile("file.dat", buf);
std::cout << "buf size: " << buf.size() << std::endl;

When I run the code, I get the following output:

all content read successfully: 323
buf size: 0

When I try to print the items in the vector like this:

for(const auto &i : buf)
{
    std::cout << std::hex << (int)i;
}
std::cout << std::dec << std::endl;

I get empty output.

Things I have checked

  • file.dat is in the same directory as the program
  • file.dat is not empty

So, is there anything I did wrong? Why is the vector empty after reading?

like image 239
JustARandomGuyOnTheInternet Avatar asked Feb 06 '26 04:02

JustARandomGuyOnTheInternet


1 Answers

reserve() allocates memory, but it doesn't register the allocated region as valid elements.

You should use resize() to add elements and size() to count the elements.

    // reserve capacity
    in.seekg(0, std::ios::end);
    //fileContent.reserve(in.tellg());
    fileContent.resize(in.tellg());
    in.clear();
    in.seekg(0, std::ios::beg);

    // read into vector
    //in.read(reinterpret_cast<char *>(fileContent.data()), fileContent.capacity());
    in.read(reinterpret_cast<char *>(fileContent.data()), fileContent.size());
like image 115
MikeCAT Avatar answered Feb 07 '26 18:02

MikeCAT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!