WinINet无法将文件下载到客户端?

时间:2010-08-22 03:09:05

标签: c++ c winapi winsock wininet

我很好奇为什么我遇到这个功能有问题。我正在将Web上的PNG文件下载到目标路径。例如,将Google图像下载到C:驱动器:

netDownloadData(“http://www.google.com/intl/en_ALL/images/srpr/logo1w.png”,“c:\ file.png”);

下载后文件大小正确。什么都没有返回假。当我尝试打开它时,它不会显示图像。任何想法都有帮助。谢谢!

以下是代码:

bool netDownloadData(const char *strSourceUrl, const char *strDestPath)
{

         HINTERNET hINet = NULL;
    HINTERNET hFile = NULL;
    char buffer[1024];
    DWORD dwRead;
    String sTemp;
    FILE *fp = NULL;
    DWORD size = 0;

    // Open a new internet session
    hINet = netInit();
    if (hINet == NULL) {
        sprintf(buffer, "Initializing WinINet failed.", strSourceUrl);
        utilLog(buffer);
        netCloseHandle(hINet);
        return false;
    }

    // Open the requested url.
    hFile = netOpenUrl(hINet, strSourceUrl);
    if (hFile == NULL) {
        sprintf(buffer, "URL failed upon loading: %s\n", strSourceUrl);
        utilLog(buffer);
        netCloseHandle(hINet);
        return false;
    }

    // Read file.
    while (InternetReadFile(hFile, buffer, 1023, &dwRead))
    {
        if (dwRead == 0)
            break;

        buffer[dwRead] = 0;

        sTemp += buffer;
        size += dwRead;
    }

    // Load information to file. 
    fp = fopen(strDestPath, "wb");
    if (fp == NULL)
        return false;

    fwrite(sTemp, size, 1, fp);
    fclose(fp); 

    InternetCloseHandle(hFile);
    InternetCloseHandle(hINet);

    return true;
}

2 个答案:

答案 0 :(得分:3)

什么数据类型是String?避免将二进制数据存储在字符串中,因为数据中的NULL可能会导致问题。只需在读取时写入缓冲区:

// Load information to file. 
fp = fopen(strDestPath, "wb");
if (fp == NULL)
    return false;

// Read file.
while (InternetReadFile(hFile, buffer, 1024, &dwRead))
{
    if (dwRead == 0)
        break;

    fwrite(buffer, dwRead, 1, fp);
}

fclose(fp); 

答案 1 :(得分:0)

看起来fwrite的第二个和第三个参数被转置。有关说明,请参阅fwrite docs

尝试:

fwrite(sTemp, 1, size, fp);