如何使用libcurl打印远程FTP目录列表?

问题描述:

我认为我应该使用CURLOPT_DIRLISTONLY,但我不确定如何继续.

I think I'm supposed to use CURLOPT_DIRLISTONLY but I'm not really sure how to proceed.

CURLcode curl_easy_setopt(CURL *handle, CURLOPT_DIRLISTONLY, long listonly);

我不确定如何拨打电话以实际打印列表.

I'm not sure how to make the call to actually print the list.

为FTP启用CURLOPT_DIRLISTONLY选项的作用基本上是仅检索文件名而不是文件详细信息(例如文件大小,日期等).在UNIX上使用普通ls(仅名称)或ls -l(列出详细信息)之间的区别.在FTP协议级别,启用CURLOPT_DIRLISTONLY将使libcurl发出NLST命令而不是LIST.然后,要获取目录列表,请执行与文件传输相同的操作,不同之处在于ftp:// URL将指向目录(而不是文件).传输的内容将在您的目录列表中.

Enabling the CURLOPT_DIRLISTONLY option for FTP has the effect of retrieving only file names instead of file details (e.g. file size, date, etc.) basically as the difference between using a plain ls (only names) or a ls -l (listing with details) on UNIX. At the FTP protocol level, enabling CURLOPT_DIRLISTONLY will make libcurl issue a NLST command rather than a LIST. Then to get the directory listing you do the same as a file transfer, with the difference that your ftp:// URL will point to a directory (and not to a file). The contents of that transfer will be your directory listing.

要显示目录列表,而不是将其保存到文件中,可以使用CURLOPT_WRITEFUNCTION选项让libcurl调用为每个数据块提供的回调函数.该功能只需要将数据fwritestdout即可显示.它应该看起来像这样:

To display the directory listing, rather than saving it to a file, you can use the CURLOPT_WRITEFUNCTION option to have libcurl call a callback function you supply for every block of data. That function only needs to fwrite the data to stdout to display it. It should look something like this:

void write_callback(void* data, size_t size, size_t nmemb, void* ptr)
{
  fwrite(data, size, nmemb, stdout);
}

int main()
{
  // ...
  curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, write_callback);
  // ...
  ret = curl_easy_perform(handle);
}