每次调用时都会有不同的结果

时间:2010-07-14 07:03:52

标签: c winapi

为什么以下代码每次运行时都不会打印相同的值? 有没有我忽略的东西?感谢。

#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;
}

1 个答案:

答案 0 :(得分:2)

您正在将.jpg文件的内容打印为C字符串。它不是一个字符串,它不会被正确地终止。您将获得.jpg中字节的某种再现,然后是随机数字符号。直到它在某处犯错误。显然足够快,以防止您的程序崩溃。