Sample code for 30+ languages & platforms
Lua

Check Whether the Last SFTP Read Failed

See more SFTP Examples

Demonstrates the Chilkat SFtp.LastReadFailed method, which returns whether the most recent read for a handle failed. The only argument is the handle. A normal end-of-file is not a failure.

Background: A chunked read loop needs to tell three outcomes apart: more data, a clean end-of-file, and an actual error such as a dropped connection or a revoked handle. LastReadFailed isolates the error case — it is false on a normal EOF read (which succeeds with zero bytes) and true for an empty, malformed, or already-closed handle — so the loop can stop cleanly on EOF but bail out with an error message on a genuine failure.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- Demonstrates the SFtp.LastReadFailed method, which returns whether the most recent read for a
-- handle failed.  The only argument is the handle.  A normal end-of-file is NOT a failure.

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 reading = true
local chunkSize = 4096
local bd = chilkat.BinData.new()
while reading do
    success = sftp:read_file_bd(handle, chunkSize, bd)

    -- Distinguish an actual read failure from a normal EOF.  On EOF the read succeeds, returns
    -- zero bytes, and LastReadFailed is false.
    if sftp:last_read_failed(handle) then
        print("Read failed: " .. sftp.last_error_text)
        return
    end

    reading = not sftp:eof(handle)
end

success = sftp:close_handle(handle)
if not success then
    print(sftp.last_error_text)
    return
end

print("Read " .. bd.num_bytes .. " bytes with no read failures.")

sftp:disconnect()