开发者

Different result everytime it is called

开发者 https://www.devze.com 2023-01-07 10:16 出处:网络
Why is it that the following code does not print the same value each time it is run? Is there something that I overlooked? Thanks.

Why is it that the following code does not print the same value each time it is run? Is there something that I overlooked? Thanks.

#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", GetL开发者_如何学编程astError( ) );

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

 return 0;
}


You are printing the content of a .jpg file as a C string. It isn't a string, it won't be zero-terminated correctly. You'll get some kind of rendition of the bytes in the .jpg, followed by a random number of characters. Until it blunders into a zero somewhere. Apparently quickly enough to prevent your program crashing.

0

精彩评论

暂无评论...
验证码 换一张
取 消