Your (new) code contains two significant errors:
data = new char[ size - 8 + 1 ]; file.seekg( 8 ); // skip the header file.read( data, size ); // <-- here data[ size ] = '\0'; // <-- and here
First, you want to read data without an 8-byte prefix, and you allocate the right amount of space (actually don't look any further). But at this point, size still contains the total number of bytes of the file, including an 8-byte prefix. Since you are asking to read size bytes and there is only size-8 bytes left, the file.read operation fails. You do not check for errors, and therefore you do not notice that file not valid at this point. With error checking, you should have seen this:
if (file) std::cout << "all characters read successfully."; else std::cout << "error: only " << file.gcount() << " could be read";
Since file invalid from this point, all operations, such as your later file.tellg() , return -1 .
The second error is data[size] = '\0' . Your buffer is not so big; it should be data[size-8] = 0; . You are currently writing to memory beyond what you previously assigned, which causes Undefined Behavior and can lead to problems later.
But this last operation clearly shows what you think of character strings. A PNG file is not a string, it is a binary data stream. Highlighting +1 for its size and setting this value to 0 (with an unnecessary "figurative" way of thinking using '\0' ) is only useful if the input file is of a string type β say, a plain text file.
A simple fix for your current problems is this (well, add error checking for all your file operations):
file.read( data, size-8 );
However, I would strongly recommend looking at a simpler file format first. The PNG file format is compact and well-documented; but it is also versatile, complicated and contains compressed data. For beginners, this is too complicated.
Start with a simpler image format. ppm is an intentionally simple format to get you started. tga , old but simple, presents you with a few more concepts, such as bit depths and color matching. Microsoft bmp has some nice little things, but it can still be considered a "newbie." If you are interested in simple compression, the basic pcx path length encoding is a good starting point. After mastering, you can watch in gif format, which uses much more complex LZW compression.
Only if you manage to implement parsers for them, you can look again at PNG.