tags:

views:

58

answers:

2

I'm able to download text documents (.html, .txt, etc) but I can't download images or exe's. I'm pretty sure that this is because I'm using a char, and those files are binary. I know that in C# I would use a byte. But what data-type would I use in this case?

    char buffer[1];
    DWORD dwRead;
    FILE * pFile;
    pFile = fopen(file,"w");
    while (InternetReadFile(hRequest, buffer, 1, &dwRead))
    {
        if(dwRead != 1) break;
        fprintf(pFile,"%s",buffer);
    }
    fclose(pFile);
+3  A: 

Your problem is not char, it is using fprintf with %s. char can hold all byte values. When a binary data chunk has a \0 (NULL) character in it, fprintf will stop outputting data at that time.

You want to use fwrite in this case.

In Windows, it is also important to use the b specifier when opening binary files.

Yann Ramin
@theatrus: Oh yeah you're right. I've deleted my answer. I do think the OP also needs to use `fopen()` with `wb` instead of `w` though, otherwise a Windows compiler will helpfully translate (and corrupt) binary files when writing them.
Matt Curtis
Exactly what I needed.
Lienau
+2  A: 

Since you are reading one byte at a time into a buffer which is not null terminated (because its size is 1), you need to output one byte at a time with either '%c' as the format string or using putc(buffer[0], pFile). As it stands, you are vulnerable to buffer overflow (as in, bad things may happen!).

If you are on a Windows platform, it would be a good idea to open the file in binary mode; it would do no harm on Unix since there is no difference between binary and text mode.

Jonathan Leffler