从直接下载URL下载URL文件可以通过以下步骤实现:
以下是一个示例代码,使用libcurl库实现从直接下载URL下载URL文件的功能:
#include <iostream>
#include <fstream>
#include <curl/curl.h>
size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
std::ofstream* file = static_cast<std::ofstream*>(userp);
file->write(static_cast<char*>(contents), size * nmemb);
return size * nmemb;
}
int main() {
std::string fileUrl = "https://example.com/file.txt";
std::string savePath = "downloaded_file.txt";
URL* curl = curl_easy_init();
if (curl) {
std::ofstream file(savePath, std::ios::binary);
if (file) {
curl_easy_setopt(curl,URLOPT_URL, fileUrl.c_str());
curl_easy_setopt(curl,URLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl,URLOPT_WRITEDATA, &file);
URLcode res = curl_easy_perform(curl);
if (res !=URLE_OK) {
std::cerr << "Failed to download file: " << curl_easy_strerror(res) << std::endl;
}
file.close();
} else {
std::cerr << "Failed to create file: " << savePath << std::endl;
}
curl_easy_cleanup(curl);
} else {
std::cerr << "Failed to initialize libcurl" << std::endl;
}
return 0;
}
这段代码使用libcurl库发送HTTP请求,并将响应的文件内容写入本地文件中。你可以将fileUrl
替换为你要下载的文件的URL地址,将savePath
替换为你要保存的本地文件路径。
领取专属 10元无门槛券
手把手带您无忧上云