简体   繁体   中英

Read whole std::ifstream to heap

I cannot work out why this isn't working. From what I can tell, it doesn't appear to be reading the whole image file... Though I cannot tell. I basically have some raw image that I'd like to read onto the heap.

unsigned char* ReadImageFromFile(const char* FILENAME, unsigned int SIZE_BYTES)
{
    unsigned char *data = (unsigned char*) malloc(SIZE_BYTES);

    std::ifstream image(FILENAME);
    image.read((char*) data, SIZE_BYTES);
    image.close();

    return data;
}

1) open the file in binary mode

2) don't return a raw pointer that needs to be freed

std::string readImageFromFile(const char* filename)
{
    std::ifstream image(filename, std::ios::binary);
    std::ostringstream data;
    data << image.rdbuf();
    return data.str();
}

Or if your prefer to write error-prone code (seems to be popular with the embedded crowd) you could do it this way:

char* readImageFromFile(const char* filename)
{
    std::ifstream image(filename, std::ios::binary);
    std::ostrstream data;
    data << image.rdbuf();
    data.freeze();
    return data.str();
}

Of course there's a good reason strstreams are deprecated.

Try std::ifstream image(FILENAME, std::ios_base::binary); (note the second argument to ifstream constructor).

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