Xbase++
Xbase++
Read Bytes from a Remote SFTP File (BinData)
See more SFTP Examples
Demonstrates the Chilkat SFtp.ReadFileBd method, which reads up to a number of bytes from the current position of an open handle and appends them to a BinData. The arguments are the handle, the maximum number of bytes, and the BinData. This example reads in chunks until end-of-file.
Background: For binary files, reading into a
BinData preserves the bytes exactly, unlike a text read that decodes through a charset. Because it appends, the chunked read loop accumulates the whole file in the BinData; each pass reads up to the chunk size and the loop repeats until Eof. Fewer bytes than requested can come back near the end of the file, which is normal.Chilkat Xbase++ Downloads
LOCAL nSuccess
LOCAL oSftp
LOCAL nPort
LOCAL cPassword
LOCAL cHandle
LOCAL oBd
LOCAL nChunkSize
LOCAL nReading
nSuccess := 0
// Demonstrates the SFtp.ReadFileBd method, which reads up to a number of bytes from the current
// position of an open handle and appends them to a BinData. The 1st argument is the handle, the
// 2nd is the maximum number of bytes, and the 3rd is the BinData.
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/image.png", "readOnly", "openExisting")
IF (oSftp:LastMethodSuccess == 0)
? oSftp:LastErrorText
oSftp:destroy()
RETURN
ENDIF
// Read the file in chunks until end-of-file, accumulating the bytes in a BinData.
oBd := CreateObject("Chilkat.BinData")
nChunkSize := 8192
nReading := 1
DO WHILE nReading
nSuccess := oSftp:ReadFileBd(cHandle, nChunkSize, oBd)
IF (oSftp:LastReadFailed(cHandle))
? oSftp:LastErrorText
oSftp:destroy()
oBd:destroy()
RETURN
ENDIF
nReading := .NOT. oSftp:Eof(cHandle)
ENDDO
nSuccess := oSftp:CloseHandle(cHandle)
IF (nSuccess == 0)
? oSftp:LastErrorText
oSftp:destroy()
oBd:destroy()
RETURN
ENDIF
? "Read " + Str(oBd:NumBytes) + " bytes."
oSftp:Disconnect()
oSftp:destroy()
oBd:destroy()