Question

I was having problem in storing .png images , fetched from HTTP server using a C code . I must mention that the images are successfully fetched from server as i analysed wireshark while running the code and content length in header matches buffer size. When i write the buffer data to a .png file using fwrite like this:

Was it helpful?

Solution

Your logic of writing upto *pt != '\0' is not correct in this loop

while((c=*pt)!='\0')
        {
            fwrite(&c, sizeof(c),1, fp);
            pt++;;
        }

There can be '\0' character anywhere in the binary data of .png file. So you will not write data after that, hence you are seeing your file size smaller than file size on server.

You should parse the HTTP headers and get value for Content-Length, which gives size of data in bytes and read those many from server and write in local file.

Look for HTTP RFC for more details about the protocol.

There are other problems in your code like

char *pt=malloc(100000);
pt=strstr(rep,"\r\n\r\n");

With this malloc() to pt is not required and leaks the memory.

OTHER TIPS

Try to open the file for output in binary mode , give FILE *fp the flag wb.

Also, why do you try to write byte by byte ? try fwrite(pt,10000,1,fp)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top