Hegde
Hegde

Reputation: 481

Reading a .bmp image with fread()

I am trying to read a .bmp image and write the data into a text file. Code is running fine but the problem is, it cannot read whole image once so I have to call fread() function many times. While doing this my code is repeatedly storing the first read data into the text file. What changes do I have to do in order to read the whole image properly? Below is my code snippet.

int size = width * height;
unsigned char* data = new unsigned char[size]; 
filename = "image.bmp";
fname = "image_data.txt";
FILE* f = fopen(filename, "rb");
FILE *fp = fopen(fname, "w");

while(totalBytes < size)
{
    readsize = fread(data, sizeof(unsigned char), size, f);
    totalBytes += readsize;
    for(i = 0; i < readsize; i++)
    {
        fprintf(fp, "%d", data[i]);
        if((i % width) == 0 && i != 0)
            fprintf(fp, "\n");
    }
    fseek(f, readsize, SEEK_SET);
    readsize = 0;
}

Upvotes: 1

Views: 11880

Answers (1)

schnaader
schnaader

Reputation: 49731

Your fseek call is wrong. After the fread call the file position will be behind the read data, so you can just read on without seeking.

What happened before was that you read X bytes, did an unnecessary but harmless fseek to file position X, then read Y bytes, but did a harmful fseek back to file position X, so you kept reading the same data again.

while(totalBytes < size)
{
    readsize=fread(data, sizeof(unsigned char), size, f);
    totalBytes+=readsize;
    for(i = 0; i < readsize; i++)
        {
          fprintf(fp,"%d",data[i]);
              if((i % width)== 0 && i!=0)
               fprintf(fp,"\n");
        }
}

Upvotes: 2

Related Questions