Sample code for 30+ languages & platforms
Visual FoxPro

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

Visual FoxPro
LOCAL lnSuccess
LOCAL loSftp
LOCAL lnPort
LOCAL lcPassword
LOCAL lcHandle
LOCAL loSbContent
LOCAL lnChunkSize
LOCAL lnReading
LOCAL lcChunk

lnSuccess = 0

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

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

*  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.
loSbContent = CreateObject('Chilkat.StringBuilder')
lnChunkSize = 4096
lnReading = 1
DO WHILE lnReading
    lcChunk = loSftp.ReadFileText(lcHandle,lnChunkSize,"utf-8")
    IF (loSftp.LastReadFailed(lcHandle)) THEN
        ? loSftp.LastErrorText
        RELEASE loSftp
        RELEASE loSbContent
        CANCEL
    ENDIF

    loSbContent.Append(lcChunk)
    lnReading = NOT loSftp.Eof(lcHandle)
ENDDO

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

? loSbContent.GetAsString()

loSftp.Disconnect()

RELEASE loSftp
RELEASE loSbContent