Xbase++
Xbase++
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 Xbase++ Downloads
LOCAL nSuccess
LOCAL oSftp
LOCAL nPort
LOCAL cPassword
LOCAL cHandle
LOCAL oSbContent
LOCAL nChunkSize
LOCAL nReading
LOCAL cChunk
nSuccess := 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.
oSftp := CreateObject("Chilkat.SFtp")
// Connect, authenticate, and initialize the SFTP subsystem.
nPort := 22
nSuccess := oSftp:Connect("sftp.example.com", nPort)
IF (nSuccess == 0)
? oSftp:LastErrorText
oSftp:destroy()
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.
cPassword := "mySshPassword"
nSuccess := oSftp:AuthenticatePw("mySshLogin", cPassword)
IF (nSuccess == 0)
? oSftp:LastErrorText
oSftp:destroy()
RETURN
ENDIF
nSuccess := oSftp:InitializeSftp()
IF (nSuccess == 0)
? oSftp:LastErrorText
oSftp:destroy()
RETURN
ENDIF
cHandle := oSftp:OpenFile("subdir/data.txt", "readOnly", "openExisting")
IF (oSftp:LastMethodSuccess == 0)
? oSftp:LastErrorText
oSftp:destroy()
RETURN
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 := CreateObject("Chilkat.StringBuilder")
nChunkSize := 4096
nReading := 1
DO WHILE nReading
cChunk := oSftp:ReadFileText(cHandle, nChunkSize, "utf-8")
IF (oSftp:LastReadFailed(cHandle))
? oSftp:LastErrorText
oSftp:destroy()
oSbContent:destroy()
RETURN
ENDIF
oSbContent:Append(cChunk)
nReading := .NOT. oSftp:Eof(cHandle)
ENDDO
nSuccess := oSftp:CloseHandle(cHandle)
IF (nSuccess == 0)
? oSftp:LastErrorText
oSftp:destroy()
oSbContent:destroy()
RETURN
ENDIF
? oSbContent:GetAsString()
oSftp:Disconnect()
oSftp:destroy()
oSbContent:destroy()