简体   繁体   中英

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?

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM