for循环从字符串link下载文件
for loop Download file from string link
我需要从 link 中批量下载一个文件,而这个 link 是一个字符串,我该怎么做?我下载了curl但是不知道怎么用
字符串是这样的:
www.example.com/item1.jpeg
www.example.com/item2.jpeg
等等。
我不需要更改输出名称,它们可以保持原样。
我正在使用这个:
CURL curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, c_str(link));
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
}
但我收到错误消息:
[Error] 'c_str' was not declared in this scope
我的整个脚本是:
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <curl/curl.h>
using namespace std;
int main ()
{
char buffer[21];
int start;
int end;
int counter;
string site;
site = "http://www.example.com/";
string extension;
extension= ".jpeg";
string link;
cout << "Start: ";
cin >> start;
cout << "End: ";
cin >> end;
for (counter=start; counter<=end; counter++)
{
std::string link = site+itoa(counter, buffer, 10)+extension;
cout << link;
cout << "\n";
//////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////
CURL curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, link.c_str());
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
}
//////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////
}
return 0;
}
错误仍然存在。
关于c_str
的错误与curl无关。相反,它表明您没有正确使用 C++ 字符串。查看文档可以看到 c_str
是字符串对象的一种方法。
http://www.cplusplus.com/reference/string/string/c_str/
因此,您很可能需要具有以下形式的内容:
#include <string>
#include <curl/curl.h>
int main () {
std::string link ("http://www.example.com/foo1.jpg");
CURL curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, link.c_str());
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
}
}