C
C
Get the Byte Count of the Last SFTP Read
See more SFTP Examples
Demonstrates the Chilkat SFtp.LastReadNumBytes method, which returns the number of bytes received by the most recent read for a handle. The only argument is the handle.
Background: SFTP reads may return fewer bytes than requested even before the end of the file, so knowing the actual count is useful for tracking progress and for advancing an explicit offset by the right amount. Both a normal EOF read and a failed read report
0, so pair this with Eof and LastReadFailed to interpret a zero-byte result correctly.Chilkat C Downloads
#include <C_CkSFtp.h>
#include <C_CkBinData.h>
void ChilkatSample(void)
{
BOOL success;
HCkSFtp sftp;
int port;
const char *password;
const char *handle;
HCkBinData bd;
int chunkSize;
BOOL reading;
int lastCount;
success = FALSE;
// Demonstrates the SFtp.LastReadNumBytes method, which returns the number of bytes received by
// the most recent read for a handle. The only argument is the handle.
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;
}
handle = CkSFtp_openFile(sftp,"subdir/data.txt","readOnly","openExisting");
if (CkSFtp_getLastMethodSuccess(sftp) == FALSE) {
printf("%s\n",CkSFtp_lastErrorText(sftp));
CkSFtp_Dispose(sftp);
return;
}
bd = CkBinData_Create();
chunkSize = 4096;
reading = TRUE;
while (reading) {
success = CkSFtp_ReadFileBd(sftp,handle,chunkSize,bd);
if (CkSFtp_LastReadFailed(sftp,handle)) {
printf("%s\n",CkSFtp_lastErrorText(sftp));
CkSFtp_Dispose(sftp);
CkBinData_Dispose(bd);
return;
}
// Report how many bytes the last read actually returned. A normal EOF read reports 0.
lastCount = CkSFtp_LastReadNumBytes(sftp,handle);
printf("Last read returned %d bytes.\n",lastCount);
reading = !CkSFtp_Eof(sftp,handle);
}
success = CkSFtp_CloseHandle(sftp,handle);
if (success == FALSE) {
printf("%s\n",CkSFtp_lastErrorText(sftp));
CkSFtp_Dispose(sftp);
CkBinData_Dispose(bd);
return;
}
printf("Total: %d bytes.\n",CkBinData_getNumBytes(bd));
CkSFtp_Disconnect(sftp);
CkSFtp_Dispose(sftp);
CkBinData_Dispose(bd);
}