Lua
Lua
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 Lua Downloads
local chilkat = require("chilkat")
-- 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.
local sftp = chilkat.SFtp.new()
-- Connect, authenticate, and initialize the SFTP subsystem.
local port = 22
local success = sftp:connect("sftp.example.com", port)
if not success then
print(sftp.last_error_text)
return
end
-- 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.
local password = "mySshPassword"
success = sftp:authenticate_pw("mySshLogin", password)
if not success then
print(sftp.last_error_text)
return
end
success = sftp:initialize_sftp()
if not success then
print(sftp.last_error_text)
return
end
local handle = sftp:open_file("subdir/data.txt", "readOnly", "openExisting")
if not sftp.last_method_success then
print(sftp.last_error_text)
return
end
local bd = chilkat.BinData.new()
local chunkSize = 4096
local reading = true
while reading do
success = sftp:read_file_bd(handle, chunkSize, bd)
if sftp:last_read_failed(handle) then
print(sftp.last_error_text)
return
end
-- Report how many bytes the last read actually returned. A normal EOF read reports 0.
local lastCount = sftp:last_read_num_bytes(handle)
print("Last read returned " .. lastCount .. " bytes.")
reading = not sftp:eof(handle)
end
success = sftp:close_handle(handle)
if not success then
print(sftp.last_error_text)
return
end
print("Total: " .. bd.num_bytes .. " bytes.")
sftp:disconnect()