2010-07-14 98 views
0

为什么每次运行时下面的代码都不打印相同的值? 有没有我忽略的东西?谢谢。每次调用时都会产生不同的结果

#include <windows.h> 
#include <stdio.h> 
#include <winhttp.h> 
#pragma comment (lib, "winhttp") 


int main(void) 
{ 
DWORD dwSize = 0; 
DWORD dwDownloaded = 0; 
LPSTR pszOutBuffer; 
BOOL bResults = FALSE; 
HINTERNET hSession = NULL, 
    hConnect = NULL, 
    hRequest = NULL; 

// Use WinHttpOpen to obtain a session handle. 
hSession = WinHttpOpen(L"WinHTTP Example/1.0", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); 

// Specify an HTTP server. 
if(hSession) 
    hConnect = WinHttpConnect(hSession, L"www.htc.com", 
    INTERNET_DEFAULT_HTTP_PORT, 0); 

// Create an HTTP request handle. 
if(hConnect) 
    hRequest = WinHttpOpenRequest(hConnect, L"GET", L"uploadedImages/Common/Shared_Image/Icons/HTC_HD2_Location.jpg", 
    NULL, WINHTTP_NO_REFERER, 
    WINHTTP_DEFAULT_ACCEPT_TYPES, 
    0); 

// Send a request. 
if(hRequest) 
    bResults = WinHttpSendRequest(hRequest, 
    WINHTTP_NO_ADDITIONAL_HEADERS, 0, 
    WINHTTP_NO_REQUEST_DATA, 0, 
    0, 0); 


// End the request. 
if(bResults) 
    bResults = WinHttpReceiveResponse(hRequest, NULL); 

// Keep checking for data until there is nothing left. 
if(bResults) 
{ 
    do 
    { 
    // Check for available data. 
    dwSize = 0; 
    if(!WinHttpQueryDataAvailable(hRequest, &dwSize)) 
    printf("Error %u in WinHttpQueryDataAvailable.\n", 
    GetLastError()); 
    // Allocate space for the buffer. 
    pszOutBuffer = new char[dwSize+1]; 
    if(!pszOutBuffer) 
    { 
    printf("Out of memory\n"); 
    dwSize=0; 
    } 
    else 
    { 
    // Read the data. 
    ZeroMemory(pszOutBuffer, dwSize+1); 

    if(!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer, 
    dwSize, &dwDownloaded)) 
    printf("Error %u in WinHttpReadData.\n", GetLastError()); 
    else 
    printf("%s", pszOutBuffer); 

    // Free the memory allocated to the buffer. 
    delete [] pszOutBuffer; 
    } 
    } while(dwSize > 0); 
} 


// Report any errors. 
if(!bResults) 
    printf("Error %d has occurred.\n", GetLastError()); 

// Close any open handles. 
if(hRequest) WinHttpCloseHandle(hRequest); 
if(hConnect) WinHttpCloseHandle(hConnect); 
if(hSession) WinHttpCloseHandle(hSession); 

return 0; 
} 

回答

2

您正在将.jpg文件的内容打印为C字符串。它不是一个字符串,它不会被正确地零终止。您将得到某种格式的.jpg中的字节格式,然后是随机数字符。直到它在某个地方变成零。显然很快就足以防止程序崩溃。

+0

感谢您的解释。我修正了它,或者更确切地说,其他人做了。这是关于SO的重复问题。 – user303907 2010-07-14 09:14:45

相关问题