本文介绍了使用libcurl检查SFTP站点上是否存在文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C ++与libcurl做SFTP / FTPS传输。在上传文件之前,我需要检查该文件是否存在,而不实际下载它。

I'm using C++ with libcurl to do SFTP/FTPS transfers. Before uploading a file, I need to check if the file exists without actually downloading it.

如果文件不存在,我遇到以下问题: p>

If the file doesn't exist, I run into the following problems:

//set up curlhandle for the public/private keys and whatever else first.
curl_easy_setopt(CurlHandle, CURLOPT_URL, "sftp://user@pass:host/nonexistent-file");
curl_easy_setopt(CurlHandle, CURLOPT_NOBODY, 1);
curl_easy_setopt(CurlHandle, CURLOPT_FILETIME, 1);
int result = curl_easy_perform(CurlHandle); 
//result is CURLE_OK, not CURLE_REMOTE_FILE_NOT_FOUND
//using curl_easy_getinfo to get the file time will return -1 for filetime, regardless
//if the file is there or not.

如果我不使用CURLOPT_NOBODY,它工作,我得到CURLE_REMOTE_FILE_NOT_FOUND。

If I don't use CURLOPT_NOBODY, it works, I get CURLE_REMOTE_FILE_NOT_FOUND.

但是,如果文件存在,它会被下载,这浪费了我的时间,因为我只是想知道它是否存在。

However, if the file does exist, it gets downloaded, which wastes time for me, since I just want to know if it's there or not.

我缺少任何其他技术/选项吗?注意,它也应该用于ftps。

Any other techniques/options I'm missing? Note that it should work for ftps as well.

编辑:sftp出现此错误。使用FTPS / FTP我得到CURLE_FTP_COULDNT_RETR_FILE,我可以使用。

This error occurs with sftp. With FTPS/FTP I get CURLE_FTP_COULDNT_RETR_FILE, which I can work with.

推荐答案

在libcurl 7.38.0

Tested this in libcurl 7.38.0

curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
curl_easy_setopt(curl, CURLOPT_HEADER, 1L);

CURLcode iRc = curl_easy_perform(curl);

if (iRc == CURLE_REMOTE_FILE_NOT_FOUND)
  // File doesn't exist
else if (iRc == CURLE_OK)
  // File exists

但是,SFTP的CURLOPT_NOBODY和CURLOPT_HEADER不会返回错误
如果某些文件不存在以前的libcurl版本。解决此问题的另一种解决方案:

However, CURLOPT_NOBODY and CURLOPT_HEADER for SFTP doesn't return an errorif file doesn't exist in some previous versions of libcurl. An alternative solution to resolve this:

// Ask for the first byte
curl_easy_setopt(curl, CURLOPT_RANGE,
    (const char *)"0-0");

CURLcode iRc = curl_easy_perform(curl);

if (iRc == CURLE_REMOTE_FILE_NOT_FOUND)
  // File doesn't exist
else if (iRc == CURLE_OK || iRc == CURLE_BAD_DOWNLOAD_RESUME)
  // File exists

这篇关于使用libcurl检查SFTP站点上是否存在文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 12:13