Lua
Lua
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 Lua Downloads
local chilkat = require("chilkat")
-- 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.
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
-- 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.
local sbContent = chilkat.StringBuilder.new()
local chunkSize = 4096
local reading = true
while reading do
local chunk = sftp:read_file_text(handle, chunkSize, "utf-8")
if sftp:last_read_failed(handle) then
print(sftp.last_error_text)
return
end
sbContent:append(chunk)
reading = not sftp:eof(handle)
end
success = sftp:close_handle(handle)
if not success then
print(sftp.last_error_text)
return
end
print(sbContent:get_as_string())
sftp:disconnect()