gpt4 book ai didi

c++ - 使用 Libcurl 从 FTP 服务器文件下载多个文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:30:59 31 4
gpt4 key购买 nike

我使用以下代码从 FTP 服务器下载所有文件

接下来的步骤是:1.创建文件的FTP列表

    getFTPList(string sHost, string sUser, string sPass, string sUri)
{
CURL *curl;
CURLcode res;
FILE *ftplister;
string host = "ftp://";
host += sHost;
host += "/sample/";
string furl = host + sUri;
string usrpwd = sUser;
usrpwd += ":";
usrpwd += sPass;
/* local file name to store the file as */
ftplister = fopen("ftp-list", "wb"); /* b is binary, needed on win32 */
curl = curl_easy_init();
if(curl) {
/* Get a file listing from sunet */
curl_easy_setopt(curl, CURLOPT_URL, furl.c_str() );
curl_easy_setopt(curl, CURLOPT_USERPWD, usrpwd.c_str());
curl_easy_setopt(curl, CURLOPT_FTPLISTONLY, TRUE);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &write_list);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, ftplister);
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);
}
fclose(ftplister); /* close the local file */
}
  1. 使用这个列表下载文件,递归调用下载函数

    int main(){
    FILE *ftpfile;
    string line;
    ftpfile = fopen("ftp-list", "r");
    ifstream infile("ftp-list");
    while ( getline(infile, line) )
    {
    string url, ofname, surl = "ftp://myhost/uploader/", sfname = "C:\\CNAP\\";
    url = surl + line;
    ofname = sfname +line;
    cout<<url<<" "<<ofname<<endl;
    char* theVal ;
    char* theStr ;
    theVal = new char [url.size()+1];
    theStr = new char [ofname.size()+1];
    strcpy(theVal, url.c_str());
    strcpy(theStr, ofname.c_str());
    downloadFile(theVal, theStr);
    }
    return 0;
    }

现在下载功能:

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written;
written = fwrite(ptr, size, nmemb, stream);
return written;
}

void downloadFile(const char* url, const char* ofname)
{
CURL *curl;
FILE *fp;
CURLcode res;
curl = curl_easy_init();
if (curl){
fp = fopen(ofname,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_USERPWD, "user:pass");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
fclose(fp);
}
}

它在实现时效果很好,但只能下载文本文件或一些带有文本的文件,如果我下载图像或 docx 或 zip 或 rar 或任何非文本文件,它会失败,无法打开下载后(说文件无效)。

我不确定我错过了什么,我们将不胜感激。

我知道这是一种低效的编码方式,但我只需要正确下载(任何文件)。提高效率是我的下一个议程。

PS: 这里使用了这个方法 Downloading multiple files with libcurl in C++

谢谢

最佳答案

下载时的文件需要以二进制文件打开

fp = fopen(ofname,"wb");

谢谢罗伯的帮助

关于c++ - 使用 Libcurl 从 FTP 服务器文件下载多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12109054/

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