gpt4 book ai didi

Curl get request in C -将html数据存储在另一个文件中

转载 作者:太空宇宙 更新时间:2023-11-04 08:27:46 24 4
gpt4 key购买 nike

我正在使用此代码使用 c 语言的 curl 请求从 Web 浏览器检索数据。我想将输出存储在另一个文件或缓冲区中。

#include <stdio.h>
#include <curl/curl.h>
#include <curl/easy.h>
int main(void)
{
CURL *curl;
CURLcode res;

curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
/* example.com is redirected, so we tell libcurl to follow redirection */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
/* Check for errors */
if(res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));

/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}

这段代码的输出是一个html文件。我想将该 html 存储在另一个文件或缓冲区中。如何做到这一点。

提前谢谢你。

最佳答案

这是对您的代码的修改,将 HTML 响应写入文件:

#include <stdio.h>
#include <curl/curl.h>
#include <curl/easy.h>
int main(void)
{
CURL *curl;
CURLcode res;

curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");

/* example.com is redirected, so we tell libcurl to follow redirection */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

/* create an output file and prepare to write the response */
FILE *output_file = fopen("output_file.html", "w");
curl_easy_setopt(curl, CURLOPT_WRITEDATA, output_file);

/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);

/* Check for errors */
if(res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %sn",
curl_easy_strerror(res));
}

/* always cleanup */
curl_easy_cleanup(curl);
}
return 0;
}

下面是一些相关的问题:

Saving a file using libcurl in C

Download file using libcurl in C/C++

关于Curl get request in C -将html数据存储在另一个文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29676160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com