I’m trying to read an image into a char array. Here is my try:
ifstream file ("htdocs/image.png", ios::in | ios::binary | ios::ate);
ifstream::pos_type fileSize;
char* fileContents;
if(file.is_open())
{
fileSize = file.tellg();
fileContents = new char[fileSize];
file.seekg(0, ios::beg);
if(!file.read(fileContents, fileSize))
{
cout << "fail to read" << endl;
}
file.close();
cout << "size: " << fileSize << endl;
cout << "sizeof: " << sizeof(fileContents) << endl;
cout << "length: " << strlen(fileContents) << endl;
cout << "random: " << fileContents[55] << endl;
cout << fileContents << endl;
}
And this is the output:
size: 1944
sizeof: 8
length: 8
random: ?
?PNG
Can anyone explain this to me? Is there an end-of-file char at position 8? This example was taken from cplusplus.com
Running Mac OS X and compiling with XCode.
Returns the size of the file. size of your
image.pngis1944 bytes.cout << "size: " << fileSize << endl;Returns the
sizeof(char*), which is8on your environment. Note that size of any pointer is always the same on any environment.cout << "sizeof: " << sizeof(fileContents) << endl;The file you are reading is a binary file so it might contain
0as a valid data. When you usestrlen, it returns the length until a0is encountered, which in the case of your file is8.cout << "length: " << strlen(fileContents) << endl;Returns the character at the
56th location(remember array indexing starts from 0) from start of file.cout << "random: " << fileContents[55] << endl;A suggestion:
Do remember to deallocate the dynamic memory allocation for
fileContentsusing:if you don’t, you will end up creating a memory leak.