Sample code for 30+ languages & platforms
AutoIt

Detect End-of-File on a Remote SFTP File

See more SFTP Examples

Demonstrates the Chilkat SFtp.Eof method, which returns whether the most recent read for a handle received the SFTP end-of-file status. The only argument is the handle. This example reads until Eof is true.

Background: The timing here is worth understanding: reading exactly through the final byte does not immediately set EOF. The next read succeeds, returns zero bytes, sets the status to SSH_FX_EOF, and only then does Eof report true. That is why the loop tests Eof after each read rather than assuming a short read means the end — a short read can also just be the server returning less than requested.

Chilkat AutoIt Downloads

AutoIt
Local $bSuccess = False

;  Demonstrates the SFtp.Eof method, which returns whether the most recent read for a handle
;  received the SFTP end-of-file status.  The only argument is the handle.

$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

;  Read until Eof reports the end of the file.  Note that reading exactly through the final byte
;  does not set EOF; the next read returns zero bytes and then Eof becomes true.
$oSbContent = ObjCreate("Chilkat.StringBuilder")
Local $iChunkSize = 4096
Local $bReading = True
While $bReading
Local $sChunk = $oSftp.ReadFileText($sHandle,$iChunkSize,"utf-8")
    If ($oSftp.LastReadFailed($sHandle)) Then
        ConsoleWrite($oSftp.LastErrorText & @CRLF)
        Exit
    EndIf

    $oSbContent.Append($sChunk)
    $bReading = Not $oSftp.Eof($sHandle)
Wend

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

ConsoleWrite($oSbContent.GetAsString() & @CRLF)

$oSftp.Disconnect