1

I'm trying to read a png file with read() and open() in C, but all I'm getting is corrupted data. Here is my code :

int  r;
int  fd;
char buff[4097];

fd = open("image.png", O_RDONLY);
while ((r = read(fd, buff, 4096)) > 0)
{
    buff[r] = '\0';
    printf("%s", buff);
}
close(fd);

The 8-10 first bytes are the same and then the data is corrupted and doesn't match at all the original image. Thanks for your help

3
  • How does this data not "match at all the original image"? Are you aware that (1) in a PNG image, the image data may not follow immediately after the header, and (2) it is LZW compressed? In other words, are you aware there is a PNG Format Specification? Commented Dec 17, 2014 at 22:47
  • 1
    Well, you are reading some binary data and try to print it with "%s" so if, for example, there is null character(0x00) in your image data you will not see the data after that character. So, it is perfectly normal that you don't get a matching result. Commented Dec 17, 2014 at 22:51
  • Okay I see! Yes I'm aware of PNG specification, I'm handling this later in my code, first I'm just trying to get the binary data in order to process it. Commented Dec 17, 2014 at 23:02

1 Answer 1

3

One should not expect to be able to read a binary file and print it as a string. In order to see what is actually in your file, print it as something more suitable for the binary format - say, hex:

int i = 0;
while ((r = read(fd, buff, 4096)) > 0) {
    for (int j = 0 ; j != r ; j++ ) {
        printf("%02x ", buff[j]);
        if (i % 16 == 0) {
            printf("\n");
        }
        i++;
    }
}
printf("\n");

Note that this code simply grabs raw bytes from your image file, without making any attempt at interpreting it. Your file may be compressed, too, so trying to interpret it may be a complex task.

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

1 Comment

And the image data in a PNG file in particular is always compressed.

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.