C++读取网络url文件内容

本文介绍了一个使用C++实现的简单控制台应用程序,该程序能够通过WinInet API从指定的URL(例如'http://www.baidu.com/xxx.txt')下载文本文件并将其内容读取到内存中。这个程序展示了如何打开Internet会话、发起请求、读取响应数据以及关闭连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


文件地址为“http://www.baidu.com/xxx.txt

// readTxt.cpp :Defines the entry point for the console application.
//
 
#include "stdafx.h"
#include <Windows.h>
#include <wininet.h>
#include <string>
using namespace std;
#pragma comment(lib, "wininet.lib")
#define BUF_SIZE 1024
 
LPSTR GetInterNetURLText(LPSTR lpcInterNetURL, char* buff);
 
int _tmain(int argc, _TCHAR* argv[])
{
    char buf[BUF_SIZE] = {0};
    char url[MAX_PATH] = "http://www.baidu.com/xxx.txt";
    GetInterNetURLText(url, buf);
 
    return 0;
}
 
LPSTR GetInterNetURLText(LPSTR lpcInterNetURL, char* buff)
{   
    HINTERNET hSession;   
    LPSTR lpResult = NULL;
    hSession = InternetOpen("WinInet", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);   
    __try
    {       
       if(hSession != NULL)        
       {          
           HINTERNET hRequest;            
           hRequest = InternetOpenUrlA(hSession,lpcInterNetURL, NULL,0, INTERNET_FLAG_RELOAD, 0);        
           __try         
           {                
              if(hRequest != NULL)        
              {           
                  DWORD dwBytesRead;                  
                  char szBuffer[BUF_SIZE] = {0};
 
                  if(InternetReadFile(hRequest, szBuffer, BUF_SIZE, &dwBytesRead))           
                  {                 
                     RtlMoveMemory(buff, szBuffer, BUF_SIZE);   
                     return 0;              
                  }               
              }           
           }__finally     
           {              
              InternetCloseHandle(hRequest);  
           }       
       }   
    }__finally    
    {       
       InternetCloseHandle(hSession);  
    }   
    return lpResult;
}


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值