Tcl
Tcl
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 Tcl Downloads
load ./chilkat.dll
set success 0
# 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.
set sftp [new_CkSFtp]
# Connect, authenticate, and initialize the SFTP subsystem.
set port 22
set success [CkSFtp_Connect $sftp "sftp.example.com" $port]
if {$success == 0} then {
puts [CkSFtp_lastErrorText $sftp]
delete_CkSFtp $sftp
exit
}
# 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.
set password "mySshPassword"
set success [CkSFtp_AuthenticatePw $sftp "mySshLogin" $password]
if {$success == 0} then {
puts [CkSFtp_lastErrorText $sftp]
delete_CkSFtp $sftp
exit
}
set success [CkSFtp_InitializeSftp $sftp]
if {$success == 0} then {
puts [CkSFtp_lastErrorText $sftp]
delete_CkSFtp $sftp
exit
}
set handle [CkSFtp_openFile $sftp "subdir/data.txt" "readOnly" "openExisting"]
if {[CkSFtp_get_LastMethodSuccess $sftp] == 0} then {
puts [CkSFtp_lastErrorText $sftp]
delete_CkSFtp $sftp
exit
}
set bd [new_CkBinData]
set chunkSize 4096
set reading 1
while {$reading} {
set success [CkSFtp_ReadFileBd $sftp $handle $chunkSize $bd]
if {CkSFtp_LastReadFailed $sftp $handle} then {
puts [CkSFtp_lastErrorText $sftp]
delete_CkSFtp $sftp
delete_CkBinData $bd
exit
}
# Report how many bytes the last read actually returned. A normal EOF read reports 0.
set lastCount [CkSFtp_LastReadNumBytes $sftp $handle]
puts "Last read returned $lastCount bytes."
set reading ![CkSFtp_Eof $sftp $handle]
}
set success [CkSFtp_CloseHandle $sftp $handle]
if {$success == 0} then {
puts [CkSFtp_lastErrorText $sftp]
delete_CkSFtp $sftp
delete_CkBinData $bd
exit
}
puts "Total: [CkBinData_get_NumBytes $bd] bytes."
CkSFtp_Disconnect $sftp
delete_CkSFtp $sftp
delete_CkBinData $bd