使用 curl 下载文件时确定扩展名

Determine extension when downloading a file with curl?

本文关键字:扩展名 文件 curl 下载 使用      更新时间:2023-10-16

>我创建了一个程序,使用 curl
从互联网下载字幕如何知道我下载的文件的扩展名(.zip或.rar)?

这是我的代码(它是函数的一部分)

FILE* download=fopen("download.zip","wb");//i assume it's a zip
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_POST,1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS,post_data.c_str());
curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)");
curl_easy_setopt(curl, CURLOPT_URL,url.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write2file);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, download);
res = curl_easy_perform(curl);
if(res != CURLE_OK)
    std::cout<<"Download Failed "<<std::endl;
curl_easy_cleanup(curl);
fclose(download);
您可以使用

curl_easy_getinfo()函数,它具有内容类型信息:

CURLINFO_CONTENT_TYPE

将指针传递给 char 指针以接收 下载的对象。这是从内容类型读取的值: 田。如果得到 NULL,则表示服务器未发送有效的 内容类型标头或使用的协议不支持此功能。

使用该信息,您可以通过在磁盘上重命名下载的文件来为其提供正确的扩展名。