PureBasic
PureBasic
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 PureBasic Downloads
IncludeFile "CkBinData.pb"
IncludeFile "CkSFtp.pb"
Procedure ChilkatExample()
success.i = 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.
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
reading.i = 1
chunkSize.i = 4096
bd.i = CkBinData::ckCreate()
If bd.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
While reading
success = CkSFtp::ckReadFileBd(sftp,handle,chunkSize,bd)
; Distinguish an actual read failure from a normal EOF. On EOF the read succeeds, returns
; zero bytes, and LastReadFailed is 0.
If CkSFtp::ckLastReadFailed(sftp,handle)
Debug "Read failed: " + CkSFtp::ckLastErrorText(sftp)
CkSFtp::ckDispose(sftp)
CkBinData::ckDispose(bd)
ProcedureReturn
EndIf
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 "Read " + Str(CkBinData::ckNumBytes(bd)) + " bytes with no read failures."
CkSFtp::ckDisconnect(sftp)
CkSFtp::ckDispose(sftp)
CkBinData::ckDispose(bd)
ProcedureReturn
EndProcedure