Saturday, 24 June 2017

c - ftell error after the first call to fread



So I have a very simple program that reads the 3 first bytes of a file:





int main(void)

{

FILE *fd = NULL;
int i;
unsigned char test = 0;
fd = fopen("test.bmp", "r");

printf("position: %ld\n", ftell(fd));


for (i=0; i<3; i++) {
fread(&test, sizeof (unsigned char), 1, fd);
printf("position: %ld char:%X\n", ftell(fd), test);
}

return (0);
}



When I try it with a text file it works fine:




position: 0
position: 1 char: 61
position: 2 char: 62
position: 3 char: 63


but when I run it with a PNG for example I get:





position: 0
position: 147 char:89
position: 148 char:50
position: 149 char:4E


Note that the 3 first bytes of the file are indeed 89 50 4E but I don't know where the 147 comes from.
With a bmp file I get:





position: 0
position: -1 char:42
position: 0 char:4D
position: 1 char:76


Do you know where these first positions come from?
Thanks a lot for your help



Answer



You need to open the file in binary mode:



fd = fopen("test.bmp", "rb");


If you try to read a binary file like a bitmap in text mode, the bytes corresponding to carriage returns and linefeeds confuse things.


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...