Yuv*_*uvi 8 c ftp resume curl libcurl
我试图使用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 %d\n", res);
}
}
if(ftpfile.stream)
fclose(ftpfile.stream); /* close the local file */
curl_global_cleanup();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以告诉我,如果连接被远程站点关闭,我该如何恢复下载.任何帮助,将不胜感激
谢谢,
Yuvi
在 ftpfile 结构中添加一个变量,以了解您的写入函数是否需要追加,并通过将 CURLOPT_RESUME_FROM 设置为已下载的字节数来告诉 libcurl 从目标文件末尾恢复下载:
struct FtpFile
{
const char *pcInfFil;
FILE *pFd;
int iAppend;
};
Run Code Online (Sandbox Code Playgroud)
主要是,如果你想恢复:
curl_easy_setopt(curl, CURLOPT_RESUME_FROM , numberOfBytesToSkip);
Run Code Online (Sandbox Code Playgroud)
如果文件尚不存在,或者不是恢复下载而是新下载,请务必将 CURLOPT_RESUME_FROM 设置回 0。
在 my_fwrite 中:
out->stream=fopen(out->filename, out->iAppend ? "ab":"wb");
Run Code Online (Sandbox Code Playgroud)
PS如果您需要恢复文件的位置大于长(2GB),请查看CURLOPT_RESUME_FROM_LARGE和CURL_OFF_T_C()
回应请求有关如何知道传输何时失败的更多信息的评论:
调用curl后轻松执行调用:
CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ... );
Run Code Online (Sandbox Code Playgroud)
从curl上下文中检索:
CURLINFO_HEADER_SIZE
CURLINFO_CONTENT_LENGTH_DOWNLOAD
Run Code Online (Sandbox Code Playgroud)
将它们加在一起并确保它们相等
CURLINFO_SIZE_DOWNLOAD
Run Code Online (Sandbox Code Playgroud)
如果没有尝试重新执行上下文。
并且一定要使用最新版本的curl,如果 60 秒没有收到来自 FTP 服务器的下载信息,它应该会超时。
| 归档时间: |
|
| 查看次数: |
5426 次 |
| 最近记录: |