我使用 C++ 和 libcurl 进行 SFTP/FTPS 传输。在上传文件之前,我需要检查文件是否存在而不实际下载它。
如果该文件不存在,我会遇到以下问题:
//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。
但是,如果该文件确实存在,则会下载它,这对我来说浪费时间,因为我只想知道它是否存在。
我还缺少其他技术/选项吗?请注意,它也适用于 ftps。
编辑: sftp 会发生此错误。通过 FTPS/FTP,我得到了 CURLE_FTP_COULDNT_RETR_FILE,我可以使用它。
在 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 的某些早期版本中不存在该文件。解决此问题的替代解决方案:
// 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)