bAp
bAp

Reputation: 13

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

Upvotes: 1

Views: 1294

Answers (3)

Jens
Jens

Reputation: 133

  • 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);

Upvotes: 0

Praveen S
Praveen S

Reputation: 10395

Please look at this question Reading bytes from bmp file.

Looks like problem is in the mode of opening it.

Upvotes: 0

anon
anon

Reputation:

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.

Upvotes: 4

Related Questions