1

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

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Please look at this question Reading bytes from bmp file.

Looks like problem is in the mode of opening it.

Comments

0
  • check if the file exists in your developer/program directory
  • check if the file is used by a other application
  • try to copy the file under a second name, and open this file
  • check the operating system: Windows use C:\Users\ , and Linux /home/user (you can see the differences ?
  • check your code, if it for Windows use: C:\\Users\\you\\filename.ext
  • check your file limit, increase it if all fails
  • and last but not least, the the file pointer to the top of file (position: 0) with fseek(filehandle,SEEK_SET);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.