1

我是 libcurl 的新手,我正在尝试使用 ftp 从服务器获取文件列表,通过这里的示例和其他一些帖子,我想出了以下代码。但是当我运行它时,它会返回错误消息:

写作主体失败 (4294967295 != 129)

在 CURLOPT_ERRORBUFFER 设置的错误字符串中。curl_easy_strerror( res )回报:

将接收到的数据写入磁盘/应用程序失败

struct FtpFile 
{
    const char *filename;
    FILE *stream;
};

static size_t fileWrite( void *buffer, size_t size, size_t nmemb, void *stream )
{
    struct FtpFile *out=(struct FtpFile *)stream;
    if(out && !out->stream) 
    {
        out->stream=fopen(out->filename, "wb");
        if(!out->stream)
        {
            cout << out->filename << " open failure [fileWrite] " << endl;
            return -1;
        }
    }

    size_t written = fwrite(buffer, size, nmemb, out->stream);    
    cout << written << endl;
    if(written <= 0)
        cout << "Nothing written : " << written;

    return written;
}

void getFileList( const char* url, const char* fname )
{
    CURL *curl;
    CURLcode res;
    FILE *ftpfile;
    const char *errmsg;


    ftpfile = fopen(fname, "wb"); 
    if ( ftpfile == NULL )
    {
        cout << fname << " open failure [getFileList] " << endl ;
        return;
    } 

    curl = curl_easy_init();
    if(curl) 
    {
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fileWrite);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, ftpfile);         
        curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errmsg);            
        curl_easy_setopt(curl, CURLOPT_USERNAME, "username");
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "password");
        curl_easy_setopt(curl, CURLOPT_FTPLISTONLY,TRUE);
        res = curl_easy_perform(curl);
        if(res != CURLE_OK)
        {
            fprintf( stderr, "curl_easy_perform() failed: %s\nError Message: %s\n", curl_easy_strerror( res ), errmsg );
        }

        curl_easy_cleanup(curl);
    }

    fclose(ftpfile);
}

int main(int argc, char *argv[])
{
    getFileList( "ftp://ftp.example.com/public/somefolder/", "file-list.txt" );

    system("PAUSE");
    return EXIT_SUCCESS;
}
4

2 回答 2

2

4294967295 是 -1 的 32 位无符号版本,这可能是您的回调返回的内容,因此 libcurl 认为这是一个错误并停止了一切。

-> 文件名在哪里分配?

您将 FILE * 传递给 CURLOPT_WRITEDATA ,但您的回调将其读取为 struct FtpFile *...

于 2012-11-21T19:14:11.107 回答
0

首先,您的fileWrite函数应该返回写入的字节数。fwrite返回写入的对象数。所以你必须return written * size;

然后,正如 Daniel Stenberg 指出的那样,您将 a 传递FILE *fileWrite但将其用作struct FtpFile *. 试试这个:

static size_t fileWrite( void *buffer, size_t size, size_t nmemb, void *stream )
{
  size_t written = fwrite(buffer, size, nmemb, (FILE*)stream);
  std::cout << written * size << std::endl;
  if(written <= 0)
    std::cout << "Nothing written : " << written;
  return written * size;
}
于 2012-11-21T17:07:58.403 回答