0
#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

3
  • 2
    Why are you using int variables when you're reading byte sized values? What is sizeof(int) on the platform you're using? Commented Dec 31, 2016 at 1:07
  • 2
    I suspect reading unsigned char sig[2] via fread(sig, sizeof(sig), 1, f) would be nearer to what you seem to want, though you probably want to take the time to read the entire header carefully. Commented Dec 31, 2016 at 1:11
  • the should be checking the returned values (not the parameter values from calls to fopen() and fread() to assure the operation(s) were successful. Commented Dec 31, 2016 at 8:30

1 Answer 1

3

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;
} 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot,that was the problem, i tried something similar before, but i was modifying the arguments of printf too (%s instead of %d) why is not this good ?
%s is for printing a string, which is an array of char ending with a null byte. i is just a single character. If you want to see the character instead of the ASCII code, use %c.
@LazuRazvan: note that printing out the character instead of its decimal value is only useful for the very first 2 bytes in a BMP file. The rest is all binary data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.