PureBasic
PureBasic
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 PureBasic Downloads
IncludeFile "CkBinData.pb"
IncludeFile "CkSFtp.pb"
Procedure ChilkatExample()
success.i = 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.
sftp.i = CkSFtp::ckCreate()
If sftp.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
; Connect, authenticate, and initialize the SFTP subsystem.
port.i = 22
success = CkSFtp::ckConnect(sftp,"sftp.example.com",port)
If success = 0
Debug CkSFtp::ckLastErrorText(sftp)
CkSFtp::ckDispose(sftp)
ProcedureReturn
EndIf
; 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.s = "mySshPassword"
success = CkSFtp::ckAuthenticatePw(sftp,"mySshLogin",password)
If success = 0
Debug CkSFtp::ckLastErrorText(sftp)
CkSFtp::ckDispose(sftp)
ProcedureReturn
EndIf
success = CkSFtp::ckInitializeSftp(sftp)
If success = 0
Debug CkSFtp::ckLastErrorText(sftp)
CkSFtp::ckDispose(sftp)
ProcedureReturn
EndIf
handle.s = CkSFtp::ckOpenFile(sftp,"subdir/data.txt","readOnly","openExisting")
If CkSFtp::ckLastMethodSuccess(sftp) = 0
Debug CkSFtp::ckLastErrorText(sftp)
CkSFtp::ckDispose(sftp)
ProcedureReturn
EndIf
bd.i = CkBinData::ckCreate()
If bd.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
chunkSize.i = 4096
reading.i = 1
While reading
success = CkSFtp::ckReadFileBd(sftp,handle,chunkSize,bd)
If CkSFtp::ckLastReadFailed(sftp,handle)
Debug CkSFtp::ckLastErrorText(sftp)
CkSFtp::ckDispose(sftp)
CkBinData::ckDispose(bd)
ProcedureReturn
EndIf
; Report how many bytes the last read actually returned. A normal EOF read reports 0.
lastCount.i = CkSFtp::ckLastReadNumBytes(sftp,handle)
Debug "Last read returned " + Str(lastCount) + " bytes."
reading = Not CkSFtp::ckEof(sftp,handle)
Wend
success = CkSFtp::ckCloseHandle(sftp,handle)
If success = 0
Debug CkSFtp::ckLastErrorText(sftp)
CkSFtp::ckDispose(sftp)
CkBinData::ckDispose(bd)
ProcedureReturn
EndIf
Debug "Total: " + Str(CkBinData::ckNumBytes(bd)) + " bytes."
CkSFtp::ckDisconnect(sftp)
CkSFtp::ckDispose(sftp)
CkBinData::ckDispose(bd)
ProcedureReturn
EndProcedure