1

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;
}
skink
  • 5,133
  • 6
  • 37
  • 58
Hegde
  • 481
  • 1
  • 8
  • 17

1 Answers1

2

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");
        }
}
schnaader
  • 49,103
  • 10
  • 104
  • 136
  • ` Also note that sizeof(unsigned char) will always be 1` -- if you can assume that the code is not running on, for example, many 16 bit DSP processors. A safe assumption, sure, but not so safe to warrant being brought up. – mah Dec 16 '12 at 15:37
  • 1
    OK, removed it. Getting a bit tired of those holy C wars ("sizeof(char) is 1", "don't cast malloc"...) here - just yesterday I used "sizeof(char)" and got a comment not to do it: http://stackoverflow.com/questions/13895073/store-an-int-in-a-char-c/13895113#13895113 – schnaader Dec 16 '12 at 15:44
  • 1
    I understand about the "don't cast malloc" holy war frustration, but the bottom line is a char is not guaranteed to be 8 bits wide. Even beyond that though, replacing the sizeof with a const is not a great idea for code maintainability purposes; if anything, I would suggest in this case to use `sizeof(*data)` so that if `data`s type changes in the future, the size intention is still met. Anyway, I +1'd your answer; I was getting ready to post about the fseek when your answer came up. – mah Dec 16 '12 at 15:47
  • @schnaader I used this code here https://pastebin.com/0y2ayrJ9 and all I get in console is 6969696969Read failed – O.Rares Apr 15 '18 at 13:34