Okay, so what I'm trying to do is to write a program that reads several TGA images and bunch them together into one bin-file for later use. I got this code from NeHe OpenGL, Tutorial 24, and it is what I use to load my images:
bool loadTGA(char *path, TextureImage *texture)
{
GLubyte TGAheader[12]={0,0,2,0,0,0,0,0,0,0,0,0};
GLubyte TGAcompare[12];
GLubyte header[6];
GLuint bytesPerPixel;
GLuint imageSize;
GLuint temp;
GLuint type=GL_RGBA;
cout << "Attempting to open '" << path << "'..\n";
FILE file = fopen(path, "rb");
if( file==NULL ||
fread(TGAcompare,1,sizeof(TGAcompare),file)!=sizeof(TGAcompare) ||
memcmp(TGAheader,TGAcompare,sizeof(TGAheader))!=0 ||
fread(header,1,sizeof(header),file)!=sizeof(header))
{
if (file == NULL){
cout << "file == NULL!\n";
return false;}
else
{
fclose(file);
return false;
}
}
texture->width = header[1] * 256 + header[0];
texture->height = header[3] * 256 + header[2];
if( texture->width <=0 ||
texture->height <=0 ||
(header[4]!=24 && header[4]!=32))
{
fclose(file);
return false;
}
texture->bpp = header[4];
bytesPerPixel = texture->bpp/8;
imageSize = texture->width*texture->height*bytesPerPixel;
texture->imageData=(GLubyte *)malloc(imageSize);
if( texture->imageData==NULL ||
fread(texture->imageData, 1, imageSize, file)!=imageSize)
{
if(texture->imageData!=NULL)
free(texture->imageData);
fclose(file);
return false;
}
for(GLuint i=0; i<GLuint(imageSize); i+=bytesPerPixel)
{
temp=texture->imageData[i];
texture->imageData[i] = texture->imageData[i + 2];
texture->imageData[i + 2] = temp;
}
fclose (file);
return true;
}
Also, if you're curious about the anatomy of that TextureImage..
typedef struct
{
GLubyte *imageData;
GLuint bpp; //Bits per pixel
GLuint width;
GLuint height;
GLuint texID;
} TextureImage;
Everything works fine when loading single images. However, when I called loadTGA from a loop, using with different filenames my program suddenly started to crash when reading the third image. So it works for image 1 and 2, but crashes at 3..
So I started flushing out couts everywhere until I could narrow it down to the if-statement starting at line 12. So I broke it apart and found out it was the line fread(TGAcompare,1,sizeof(TGAcompare),file)
that caused my program to terminate. I have no chance of checking what it returns, since the program seems to terminate during the execution of fread. I receive no warnings/errors during compile (using Dev-Cpp, WinXP)
Some things I've checked:
- file is open and exist
- it is not empty, and has not reached EOF
- it's not because of a damaged file, since I tried reading img1.tga->img2.tga->img1.tga instead of img1.tga->img2.tga->img3.tga. Still crash at third image.
I'm all out of ideas, and I'm quite frustrated. Does anyone have a clue to what might cause this to happen?
Thanks a lot for your time!
Emil Olofsson