Xbase++
Xbase++
Check Whether the Last SFTP Read Failed
See more SFTP Examples
Demonstrates the Chilkat SFtp.LastReadFailed method, which returns whether the most recent read for a handle failed. The only argument is the handle. A normal end-of-file is not a failure.
Background: A chunked read loop needs to tell three outcomes apart: more data, a clean end-of-file, and an actual error such as a dropped connection or a revoked handle.
LastReadFailed isolates the error case — it is false on a normal EOF read (which succeeds with zero bytes) and true for an empty, malformed, or already-closed handle — so the loop can stop cleanly on EOF but bail out with an error message on a genuine failure.Chilkat Xbase++ Downloads
LOCAL nSuccess
LOCAL oSftp
LOCAL nPort
LOCAL cPassword
LOCAL cHandle
LOCAL nReading
LOCAL nChunkSize
LOCAL oBd
nSuccess := 0
// Demonstrates the SFtp.LastReadFailed method, which returns whether the most recent read for a
// handle failed. The only argument is the handle. A normal end-of-file is NOT a failure.
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
nReading := 1
nChunkSize := 4096
oBd := CreateObject("Chilkat.BinData")
DO WHILE nReading
nSuccess := oSftp:ReadFileBd(cHandle, nChunkSize, oBd)
// Distinguish an actual read failure from a normal EOF. On EOF the read succeeds, returns
// zero bytes, and LastReadFailed is 0.
IF (oSftp:LastReadFailed(cHandle))
? "Read failed: " + oSftp:LastErrorText
oSftp:destroy()
oBd:destroy()
RETURN
ENDIF
nReading := .NOT. oSftp:Eof(cHandle)
ENDDO
nSuccess := oSftp:CloseHandle(cHandle)
IF (nSuccess == 0)
? oSftp:LastErrorText
oSftp:destroy()
oBd:destroy()
RETURN
ENDIF
? "Read " + Str(oBd:NumBytes) + " bytes with no read failures."
oSftp:Disconnect()
oSftp:destroy()
oBd:destroy()