Save cURL content result into a string in C++

前端 未结 7 1886
鱼传尺愫
鱼传尺愫 2020-11-30 22:16
int main(void)
{
  CURL *curl;
  CURLcode res;

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, \"http://www.google.com\");
    curl_         


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 23:04

    Based on @JoachimIsaksson answer, here is a more verbose output that handles out-of-memory and has a limit for the maximum output from curl (as CURLOPT_MAXFILESIZE limits only based on header information and not on the actual size transferred ).

    #DEFINE MAX_FILE_SIZE = 10485760 //10 MiB
    
    size_t curl_to_string(void *ptr, size_t size, size_t count, void *stream)
    {
        if(((string*)stream)->size() + (size * count) > MAX_FILE_SIZE)
        {
            cerr<size()<<"bytes + buffer:"<<(size * count) << "bytes) would exceed the MAX_FILE_SIZE ("<append((char*)ptr, 0, size*count);
                break;// successful
            }catch (const std::bad_alloc&) {
                retry++;
                if(retry>100)
                {
                    cerr<

提交回复
热议问题