我正在尝试使用FTP下载文件,在此期间,如果连接终止,则应从停止的位置恢复。我的问题是,使用以下代码片段,如果我关闭连接,然后再次连接,我可以继续下载,但如果我在服务器站点这样做,我就无法恢复下载,程序将进入无限状态。
#include <stdio.h>
#include <curl/curl.h>
/*
* This is an example showing how to get a single file from an FTP server.
* It delays the actual destination file creation until the first write
* callback so that it won't create an empty file in case the remote file
* doesn't exist or something else fails.
*/
struct FtpFile {
const char *filename;
FILE *stream;
};
static size_t my_fwrite(void *buffer, size_t size, size_t nmemb, void *stream)
{
struct FtpFile *out=(struct FtpFile *)stream;
if(out && !out->stream) {
/* open file for writing */
out->stream=fopen(out->filename, "wb");
if(!out->stream)
return -1; /* failure, can't open file to write */
}
return fwrite(buffer, size, nmemb, out->stream);
}
int main(void)
{
CURL *curl;
CURLcode res;
struct FtpFile ftpfile={
"dev.zip", /* name to store the file as if succesful */
NULL
};
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
/*
* You better replace the URL with one that works!
*/
curl_easy_setopt(curl, CURLOPT_URL,
"ftp://root:password@192.168.10.1/dev.zip");
/* Define our callback to get called when there's data to be written */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite);
/* Set a pointer to our struct to pass to the callback */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile);
/* Switch on full protocol/debug output */
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
if(CURLE_OK != res) {
/* we failed */
fprintf(stderr, "curl told us %dn", res);
}
}
if(ftpfile.stream)
fclose(ftpfile.stream); /* close the local file */
curl_global_cleanup();
return 0;
}
有人能告诉我,如果连接被远程站点关闭,我该如何恢复下载吗。如有任何帮助,将不胜感激
谢谢,
Yuvi
在ftpfile结构中添加一个可变对象,以使您的写入函数知道需要出现,并通过将CURLOPT_resume_from设置为已下载的字节数来告诉libcurl从目标文件的末尾恢复下载:
struct FtpFile
{
const char *pcInfFil;
FILE *pFd;
int iAppend;
};
总的来说,如果你想继续:
curl_easy_setopt(curl, CURLOPT_RESUME_FROM , numberOfBytesToSkip);
如果该文件不存在,或者不是恢复的下载而是新的下载,请确保将CURLOPT_RESUME_FROM设置回0。
在my_frite:中
out->stream=fopen(out->filename, out->iAppend ? "ab":"wb");
第页。S.如果需要恢复文件的位置大于一个长(2GB),请查看CURLOPT_resume_FROM_LARGE和CURL_OFF_T_C()
针对请求关于如何知道何时传输失败的额外信息的评论:
呼叫curl后轻松执行呼叫:
CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ... );
从curl上下文检索:
CURLINFO_HEADER_SIZE
CURLINFO_CONTENT_LENGTH_DOWNLOAD
将它们相加,确保它们等于
CURLINFO_SIZE_DOWNLOAD
如果没有,请尝试重新编排上下文。
请确保使用最新版本的curl,它应该在60秒后超时,因为它没有收到从FTP服务器下载的消息。
您可以使用CURLOPT_CONNECTTIMEOUT和CURLOPT_TIMEOUT参数来指定每个句柄的连接超时和最大执行时间。
另一种方法(只有当您使用的是简单接口,而不是多接口时才有效)是使用套接字选项回调,您可以使用CURLOPT_SOCKOPTFUNCTION进行设置。在它中,您必须为SO_RCVTIMEO参数调用setsockopt(),直到连接在被丢弃之前可以空闲的最长时间。即,如果在最后5秒内没有接收到字节,则断开连接。