C
C
Open a Remote Directory on an SFTP Server
See more SFTP Examples
Demonstrates the Chilkat SFtp.OpenDir method, which opens a remote directory and returns a handle for reading its entries. The only argument is the directory path. Close the handle with CloseHandle when finished.
Background: Listing a directory in SFTP is a handle-based operation, mirroring file access: open the directory to get a handle, read its entries, then close it. The handle is passed to
ReadDirListing to retrieve the names and attributes. As with file handles, the directory handle is a server-side resource that should be closed to avoid exhausting the server's limits.Chilkat C Downloads
#include <C_CkSFtp.h>
void ChilkatSample(void)
{
BOOL success;
HCkSFtp sftp;
int port;
const char *password;
const char *handle;
success = FALSE;
// Demonstrates the SFtp.OpenDir method, which opens a remote directory and returns a handle for
// reading its entries. The only argument is the directory path.
sftp = CkSFtp_Create();
// Connect, authenticate, and initialize the SFTP subsystem.
port = 22;
success = CkSFtp_Connect(sftp,"sftp.example.com",port);
if (success == FALSE) {
printf("%s\n",CkSFtp_lastErrorText(sftp));
CkSFtp_Dispose(sftp);
return;
}
// Normally you would not hard-code the password in source. You should instead obtain it
// from an interactive prompt, environment variable, or a secrets vault.
password = "mySshPassword";
success = CkSFtp_AuthenticatePw(sftp,"mySshLogin",password);
if (success == FALSE) {
printf("%s\n",CkSFtp_lastErrorText(sftp));
CkSFtp_Dispose(sftp);
return;
}
success = CkSFtp_InitializeSftp(sftp);
if (success == FALSE) {
printf("%s\n",CkSFtp_lastErrorText(sftp));
CkSFtp_Dispose(sftp);
return;
}
// Open the remote directory. OpenDir returns a handle string.
handle = CkSFtp_openDir(sftp,"subdir");
if (CkSFtp_getLastMethodSuccess(sftp) == FALSE) {
printf("%s\n",CkSFtp_lastErrorText(sftp));
CkSFtp_Dispose(sftp);
return;
}
printf("Opened directory, handle = %s\n",handle);
// The directory entries are read with ReadDirListing using this handle.
// Close the handle when finished.
success = CkSFtp_CloseHandle(sftp,handle);
if (success == FALSE) {
printf("%s\n",CkSFtp_lastErrorText(sftp));
CkSFtp_Dispose(sftp);
return;
}
CkSFtp_Disconnect(sftp);
CkSFtp_Dispose(sftp);
}