C
C
Download Text from an SFTP Server (StringBuilder)
See more SFTP Examples
Demonstrates the Chilkat SFtp.DownloadSb method, which downloads a remote text file, decodes it with the given charset, and appends the text to a StringBuilder. The arguments are the remote file path, the charset, and the StringBuilder.
Note: This example uses relative local paths, which are resolved against the application's current working directory. Absolute local paths may also be used. Supply the paths appropriate to your own environment.
Background: When the remote file is text and you want its content as characters rather than raw bytes, this decodes it in one step so you can parse or display it directly. The charset must match how the file is actually encoded, or the text will be garbled. Like
DownloadBd it appends, so clear the StringBuilder first if you want only this file's text.Chilkat C Downloads
#include <C_CkSFtp.h>
#include <C_CkStringBuilder.h>
void ChilkatSample(void)
{
BOOL success;
HCkSFtp sftp;
int port;
const char *password;
HCkStringBuilder sb;
const char *fileText;
success = FALSE;
// Demonstrates the SFtp.DownloadSb method, which downloads a remote text file, decodes it, and
// appends the text to a StringBuilder. The 1st argument is the remote file path, the 2nd is the
// charset, and the 3rd is the StringBuilder.
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;
}
// Download the remote text file, decoding it as UTF-8. Existing text in the StringBuilder is
// preserved, so clear it first if you want replacement rather than append behavior.
sb = CkStringBuilder_Create();
success = CkSFtp_DownloadSb(sftp,"subdir/inventory.csv","utf-8",sb);
if (success == FALSE) {
printf("%s\n",CkSFtp_lastErrorText(sftp));
CkSFtp_Dispose(sftp);
CkStringBuilder_Dispose(sb);
return;
}
printf("Characters downloaded: %d\n",CkStringBuilder_getLength(sb));
fileText = CkStringBuilder_getAsString(sb);
printf("%s\n",fileText);
CkSFtp_Disconnect(sftp);
CkSFtp_Dispose(sftp);
CkStringBuilder_Dispose(sb);
}