Sample code for 30+ languages & platforms
AutoIt

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

AutoIt
Local $bSuccess = False

;  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 = 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

$oBd = ObjCreate("Chilkat.BinData")
Local $iChunkSize = 4096
Local $bReading = True
While $bReading
    $bSuccess = $oSftp.ReadFileBd($sHandle,$iChunkSize,$oBd)
    If ($oSftp.LastReadFailed($sHandle)) Then
        ConsoleWrite($oSftp.LastErrorText & @CRLF)
        Exit
    EndIf

    ;  Report how many bytes the last read actually returned.  A normal EOF read reports 0.
Local $iLastCount = $oSftp.LastReadNumBytes($sHandle)
    ConsoleWrite("Last read returned " & $iLastCount & " bytes." & @CRLF)

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

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

ConsoleWrite("Total: " & $oBd.NumBytes & " bytes." & @CRLF)

$oSftp.Disconnect