Xbase++
Xbase++
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 Xbase++ Downloads
LOCAL nSuccess
LOCAL oSftp
LOCAL nPort
LOCAL cPassword
LOCAL cHandle
LOCAL oBd
LOCAL nChunkSize
LOCAL nReading
LOCAL nLastCount
nSuccess := 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.
oSftp := CreateObject("Chilkat.SFtp")
// Connect, authenticate, and initialize the SFTP subsystem.
nPort := 22
nSuccess := oSftp:Connect("sftp.example.com", nPort)
IF (nSuccess == 0)
? oSftp:LastErrorText
oSftp:destroy()
RETURN
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.
cPassword := "mySshPassword"
nSuccess := oSftp:AuthenticatePw("mySshLogin", cPassword)
IF (nSuccess == 0)
? oSftp:LastErrorText
oSftp:destroy()
RETURN
ENDIF
nSuccess := oSftp:InitializeSftp()
IF (nSuccess == 0)
? oSftp:LastErrorText
oSftp:destroy()
RETURN
ENDIF
cHandle := oSftp:OpenFile("subdir/data.txt", "readOnly", "openExisting")
IF (oSftp:LastMethodSuccess == 0)
? oSftp:LastErrorText
oSftp:destroy()
RETURN
ENDIF
oBd := CreateObject("Chilkat.BinData")
nChunkSize := 4096
nReading := 1
DO WHILE nReading
nSuccess := oSftp:ReadFileBd(cHandle, nChunkSize, oBd)
IF (oSftp:LastReadFailed(cHandle))
? oSftp:LastErrorText
oSftp:destroy()
oBd:destroy()
RETURN
ENDIF
// Report how many bytes the last read actually returned. A normal EOF read reports 0.
nLastCount := oSftp:LastReadNumBytes(cHandle)
? "Last read returned " + Str(nLastCount) + " bytes."
nReading := .NOT. oSftp:Eof(cHandle)
ENDDO
nSuccess := oSftp:CloseHandle(cHandle)
IF (nSuccess == 0)
? oSftp:LastErrorText
oSftp:destroy()
oBd:destroy()
RETURN
ENDIF
? "Total: " + Str(oBd:NumBytes) + " bytes."
oSftp:Disconnect()
oSftp:destroy()
oBd:destroy()