3

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?

1 Answer 1

5

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.