Sample code for 30+ languages & platforms
AutoIt

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 AutoIt Downloads

AutoIt
Local $bSuccess = False

;  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 = ObjCreate("Chilkat.SFtp")

;  Connect, authenticate, and initialize the SFTP subsystem.
Local $iPort = 22
$bSuccess = $oSftp.Connect("sftp.example.com",$iPort)
If ($bSuccess = False) Then
    ConsoleWrite($oSftp.LastErrorText & @CRLF)
    Exit
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.
Local $sPassword = "mySshPassword"

$bSuccess = $oSftp.AuthenticatePw("mySshLogin",$sPassword)
If ($bSuccess = False) Then
    ConsoleWrite($oSftp.LastErrorText & @CRLF)
    Exit
EndIf

$bSuccess = $oSftp.InitializeSftp()
If ($bSuccess = False) Then
    ConsoleWrite($oSftp.LastErrorText & @CRLF)
    Exit
EndIf

Local $sHandle = $oSftp.OpenFile("subdir/data.txt","readOnly","openExisting")
If ($oSftp.LastMethodSuccess = False) Then
    ConsoleWrite($oSftp.LastErrorText & @CRLF)
    Exit
EndIf

Local $bReading = True
Local $iChunkSize = 4096
$oBd = ObjCreate("Chilkat.BinData")
While $bReading
    $bSuccess = $oSftp.ReadFileBd($sHandle,$iChunkSize,$oBd)

    ;  Distinguish an actual read failure from a normal EOF.  On EOF the read succeeds, returns
    ;  zero bytes, and LastReadFailed is False.
    If ($oSftp.LastReadFailed($sHandle)) Then
        ConsoleWrite("Read failed: " & $oSftp.LastErrorText & @CRLF)
        Exit
    EndIf

    $bReading = Not $oSftp.Eof($sHandle)
Wend

$bSuccess = $oSftp.CloseHandle($sHandle)
If ($bSuccess = False) Then
    ConsoleWrite($oSftp.LastErrorText & @CRLF)
    Exit
EndIf

ConsoleWrite("Read " & $oBd.NumBytes & " bytes with no read failures." & @CRLF)

$oSftp.Disconnect