Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using libcurl to check if a file exists on a SFTP site

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.

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.

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.

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


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

like image 659
Snazzer Avatar asked Sep 03 '25 14:09

Snazzer


1 Answers

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

However, CURLOPT_NOBODY and CURLOPT_HEADER for SFTP doesn't return an error if 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
like image 184
Mukul Gupta Avatar answered Sep 05 '25 03:09

Mukul Gupta