【发布时间】:2013-09-19 09:40:56
【问题描述】:
我正在从 Java 切换到 C++,这真的很痛苦。我坚持从 ftp 下载文件。我正在尝试下载一个包含一些文本的文本文件,我只想将此文本保存为字符串而不保存文件。
我从 libcurl 站点获得了以下代码:
#include <stdio.h>
#include <curl/curl.h>
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={
"curl.tar.gz", /* name to store the file as if succesful */
NULL
};
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL,
"ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/KLAX.TXT");
/* 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;
}
不幸的是,它提供了很多关于我的连接状态和文件本身的信息,但它实际上并没有给我文件的内容。我究竟做错了什么?另外,如何将内容保存在变量中?
非常感谢!
【问题讨论】:
-
你的 write 函数被调用了吗? - 仅供参考,我只是逐字复制并将其转储到 XCode 中并运行它并下载文件。它会将其下载到您运行它的位置。
-
SB,谢谢!我又做了一次,它奏效了。但是,现在我在根目录中有一个 txt 文件(我将 .gz 替换为 .txt)。您知道如何将文件的内容解析为字符串而不将其保存为文本文件吗?再次,非常感谢!
标签: c++ text ftp download libcurl