Sample code for 30+ languages & platforms
Lianja

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

Lianja
llSuccess = .F.

//  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.

loSftp = createobject("CkSFtp")

//  Connect, authenticate, and initialize the SFTP subsystem.
lnPort = 22
llSuccess = loSftp.Connect("sftp.example.com",lnPort)
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    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.
lcPassword = "mySshPassword"

llSuccess = loSftp.AuthenticatePw("mySshLogin",lcPassword)
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

llSuccess = loSftp.InitializeSftp()
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

lcHandle = loSftp.OpenFile("subdir/data.txt","readOnly","openExisting")
if (loSftp.LastMethodSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

loBd = createobject("CkBinData")
lnChunkSize = 4096
llReading = .T.
do while llReading
    llSuccess = loSftp.ReadFileBd(lcHandle,lnChunkSize,loBd)
    if (loSftp.LastReadFailed(lcHandle)) then
        ? loSftp.LastErrorText
        release loSftp
        release loBd
        return
    endif

    //  Report how many bytes the last read actually returned.  A normal EOF read reports 0.
    lnLastCount = loSftp.LastReadNumBytes(lcHandle)
    ? "Last read returned " + str(lnLastCount) + " bytes."

    llReading = not loSftp.Eof(lcHandle)
enddo

llSuccess = loSftp.CloseHandle(lcHandle)
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    release loBd
    return
endif

? "Total: " + str(loBd.NumBytes) + " bytes."

loSftp.Disconnect()


release loSftp
release loBd