Delphi DLL
Delphi DLL
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 Delphi DLL Downloads
var
success: Boolean;
sftp: HCkSFtp;
port: Integer;
password: PWideChar;
handle: PWideChar;
bd: HCkBinData;
chunkSize: Integer;
reading: Boolean;
lastCount: Integer;
begin
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) then
begin
Memo1.Lines.Add(CkSFtp__lastErrorText(sftp));
Exit;
end;
// 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) then
begin
Memo1.Lines.Add(CkSFtp__lastErrorText(sftp));
Exit;
end;
success := CkSFtp_InitializeSftp(sftp);
if (success = False) then
begin
Memo1.Lines.Add(CkSFtp__lastErrorText(sftp));
Exit;
end;
handle := CkSFtp__openFile(sftp,'subdir/data.txt','readOnly','openExisting');
if (CkSFtp_getLastMethodSuccess(sftp) = False) then
begin
Memo1.Lines.Add(CkSFtp__lastErrorText(sftp));
Exit;
end;
bd := CkBinData_Create();
chunkSize := 4096;
reading := True;
while reading do
begin
success := CkSFtp_ReadFileBd(sftp,handle,chunkSize,bd);
if (CkSFtp_LastReadFailed(sftp,handle)) then
begin
Memo1.Lines.Add(CkSFtp__lastErrorText(sftp));
Exit;
end;
// Report how many bytes the last read actually returned. A normal EOF read reports 0.
lastCount := CkSFtp_LastReadNumBytes(sftp,handle);
Memo1.Lines.Add('Last read returned ' + IntToStr(lastCount) + ' bytes.');
reading := not CkSFtp_Eof(sftp,handle);
end;
success := CkSFtp_CloseHandle(sftp,handle);
if (success = False) then
begin
Memo1.Lines.Add(CkSFtp__lastErrorText(sftp));
Exit;
end;
Memo1.Lines.Add('Total: ' + IntToStr(CkBinData_getNumBytes(bd)) + ' bytes.');
CkSFtp_Disconnect(sftp);
CkSFtp_Dispose(sftp);
CkBinData_Dispose(bd);