0

我在谷歌上找到了这段代码并做了一些调整。就这样没有问题。但是,我在输出文件的开头有很多空行来。我不知道我怎么能摆脱这个。

我尝试从 php 获取数据。

$echo "hello file";

和 C++

int main()
{

HINTERNET connect = InternetOpen("MyBrowser",0 ,0, 0, 0);

   if(!connect){
      cout<<"Connection Failed or Syntax error";
      return 0;
   }


HINTERNET OpenAddress = InternetOpenUrl(connect, http://www.myurl.com/winapi.php", 0, 0, 0, 0);

  if ( !OpenAddress )
   {
      DWORD ErrorNum = GetLastError();
      cout<<"Failed to open URL \nError No: "<<ErrorNum;
      InternetCloseHandle(connect);
      return 0;
   }

   char DataReceived[4096];
   DWORD NumberOfBytesRead = 0;
    ofstream data;
    data.open("output.txt");

   while(InternetReadFile(OpenAddress, DataReceived, 4096, 
        &NumberOfBytesRead) && NumberOfBytesRead) {        
        DataReceived[NumberOfBytesRead]='\x00';
        data<< DataReceived;    
}


     system( "pause" );
}

在文件开头的空行太多了。如何删除它们?

4

1 回答 1

0

如果InternetReadFile()实际读取 4096 个字节,则会出现缓冲区溢出。您不需要空终止缓冲区,只需使用write()方法而不是<<运算符将缓冲区按原样写入实际读取的字节数:

int main()
{
    HINTERNET connect = InternetOpen("MyBrowser",0 ,0, 0, 0);
    if (!connect)
    {
       cout << "Connection Failed or Syntax error";
       return 0;
    }

    HINTERNET OpenAddress = InternetOpenUrl(connect, "http://www.myurl.com/winapi.php", 0, 0, 0, 0);
    if (!OpenAddress)
    {
        DWORD ErrorNum = GetLastError();
        cout << "Failed to open URL" << endl << " Error No: " << ErrorNum;
        InternetCloseHandle(connect);
        return 0;
    }

    ofstream data("output.txt");
    if (!data)
    {
        cout << "Failed to open txt file";
        InternetCloseHandle(OpenAddress);
        InternetCloseHandle(connect);
        return 0;
    }

    char DataReceived[4096];
    DWORD NumberOfBytesRead = 0;

    do
    {
        if (!InternetReadFile(OpenAddress, DataReceived, 4096, &NumberOfBytesRead))
        {
            DWORD ErrorNum = GetLastError();
            cout << "Failed to read from URL" << endl << " Error No: " << ErrorNum;
            InternetCloseHandle(OpenAddress);
            InternetCloseHandle(connect);
            return 0;
        }

        if (NumberOfBytesRead == 0)
            break;

        data.write(DataReceived, NumberOfBytesRead);    
    }
    while (true);

    cout << "Finished reading from URL";
    system( "pause" );

    return 0;
}

话虽如此,如果您仍然看到文件中出现额外的行,则使用数据包嗅探器检查 PHP 实际传输的数据,并确保它没有发送额外的空白行。如果是,那么您需要解决 PHP 端的问题,而不是客户端。

于 2013-03-08T20:45:35.800 回答