Sample code for 30+ languages & platforms
Visual FoxPro

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 Visual FoxPro Downloads

Visual FoxPro
LOCAL lnSuccess
LOCAL loSftp
LOCAL lnPort
LOCAL lcPassword
LOCAL lcHandle
LOCAL loBd
LOCAL lnChunkSize
LOCAL lnReading
LOCAL lnLastCount

lnSuccess = 0

*  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('Chilkat.SFtp')

*  Connect, authenticate, and initialize the SFTP subsystem.
lnPort = 22
lnSuccess = loSftp.Connect("sftp.example.com",lnPort)
IF (lnSuccess = 0) THEN
    ? loSftp.LastErrorText
    RELEASE loSftp
    CANCEL
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"

lnSuccess = loSftp.AuthenticatePw("mySshLogin",lcPassword)
IF (lnSuccess = 0) THEN
    ? loSftp.LastErrorText
    RELEASE loSftp
    CANCEL
ENDIF

lnSuccess = loSftp.InitializeSftp()
IF (lnSuccess = 0) THEN
    ? loSftp.LastErrorText
    RELEASE loSftp
    CANCEL
ENDIF

lcHandle = loSftp.OpenFile("subdir/data.txt","readOnly","openExisting")
IF (loSftp.LastMethodSuccess = 0) THEN
    ? loSftp.LastErrorText
    RELEASE loSftp
    CANCEL
ENDIF

loBd = CreateObject('Chilkat.BinData')
lnChunkSize = 4096
lnReading = 1
DO WHILE lnReading
    lnSuccess = loSftp.ReadFileBd(lcHandle,lnChunkSize,loBd)
    IF (loSftp.LastReadFailed(lcHandle)) THEN
        ? loSftp.LastErrorText
        RELEASE loSftp
        RELEASE loBd
        CANCEL
    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."

    lnReading = NOT loSftp.Eof(lcHandle)
ENDDO

lnSuccess = loSftp.CloseHandle(lcHandle)
IF (lnSuccess = 0) THEN
    ? loSftp.LastErrorText
    RELEASE loSftp
    RELEASE loBd
    CANCEL
ENDIF

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

loSftp.Disconnect()

RELEASE loSftp
RELEASE loBd