Using libcurl to check if a file exists on an SFTP site

I am using C ++ with libcurl to transmit SFTP / FTPS. Before downloading the file, I need to check if the file exists without downloading it.

If the file does not exist, I encounter 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.

If I do not use CURLOPT_NOBODY, it works, I get CURLE_REMOTE_FILE_NOT_FOUND.

However, if the file exists, it is uploaded, which spends time on me, since I just want to know if it is there or not.

Any other methods / options that I am missing? Please note that it should work for ftps as well.


Edit: this error occurs using sftp. With FTPS / FTP, I get CURLE_FTP_COULDNT_RETR_FILE that I can work with.

+3
2

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

CURLOPT_NOBODY CURLOPT_HEADER SFTP 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
+2

. - , , , . , cURL " ", " ":

static size_t abort_read(void *ptr, size_t size, size_t nmemb, void *data)
{
  (void)ptr;
  (void)data;
  /* we are not interested in the data itself,
     so we abort operation ... */ 
  return (size_t)(-1); // produces CURLE_WRITE_ERROR
}
....
curl_easy_setopt(curl,CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, abort_read);
CURLcode res = curl_easy_perform(curl);
/* restore options */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, NULL);
curl_easy_setopt(curl, CURLOPT_URL, NULL);
return (res==CURLE_WRITE_ERROR);
0

Source: https://habr.com/ru/post/1737687/


All Articles