Reputation: 69
#include <stdio.h>
int main()
{
int i,j;
FILE *f;
f=fopen("./pathto/sth.bmp","rb");
fread(&i,1, 1, f);
printf("%d ",i);
fread(&j,1, 1, f);
printf("%d ",j);
return 0;
}
I want to read the first 2 values from a bmp file. I know that they are 66 and 77 . The problem is that if i read only the first value the variable "i" becomes 66 which is good. But if i read the second value , as "j" , then "j" becomes 77 which is good , and "i" takes a random value something like 196540 and i don't understand why. So if i read the first value everything is ok. If i read the first 2 values, the last value is good, but the first modifies, it becomes a random one , sth like 196540
Upvotes: 0
Views: 95
Reputation: 782785
When I try your program I get garbage results for both variables.
The problem is that you're using the wrong type variables. You're reading a single byte from the file, but you're reading it into an int
variable, which is multiple bytes. So this combines the single byte from the file with whatever random data happens to be in the initial values of the variables.
Declare them as char
instead of int
.
#include <stdio.h>
int main()
{
char i,j;
FILE *f;
f=fopen("sth.bmp","rb");
fread(&i,1, 1, f);
printf("%d ",i);
fread(&j,1, 1, f);
printf("%d\n",j);
return 0;
}
Upvotes: 3