简体   繁体   English

每次调用时结果不同

[英]Different result everytime it is called

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", GetLastError( ) );

 // 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. 您正在将.jpg文件的内容打印为C字符串。 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. 您将获得.jpg字节的某种形式的再现,其后是随机数量的字符。 Until it blunders into a zero somewhere. 直到它在某处突然变成零为止。 Apparently quickly enough to prevent your program crashing. 显然足够快以防止您的程序崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM