Sample code for 30+ languages & platforms
Swift

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 Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    //  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.

    let sftp = CkoSFtp()!

    //  Connect, authenticate, and initialize the SFTP subsystem.
    var port: Int = 22
    success = sftp.connect(hostname: "sftp.example.com", port: port)
    if success == false {
        print("\(sftp.lastErrorText!)")
        return
    }

    //  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.
    var password: String? = "mySshPassword"

    success = sftp.authenticatePw(login: "mySshLogin", password: password)
    if success == false {
        print("\(sftp.lastErrorText!)")
        return
    }

    success = sftp.initializeSftp()
    if success == false {
        print("\(sftp.lastErrorText!)")
        return
    }

    var handle: String? = sftp.openFile(filename: "subdir/data.txt", access: "readOnly", createDisp: "openExisting")
    if sftp.lastMethodSuccess == false {
        print("\(sftp.lastErrorText!)")
        return
    }

    var reading: Bool = true
    var chunkSize: Int = 4096
    let bd = CkoBinData()!
    while reading {
        success = sftp.readFileBd(handle: handle, numBytes: chunkSize, bd: bd)

        //  Distinguish an actual read failure from a normal EOF.  On EOF the read succeeds, returns
        //  zero bytes, and LastReadFailed is false.
        if sftp.lastReadFailed(sftpHandle: handle) {
            print("Read failed: \(sftp.lastErrorText!)")
            return
        }

        reading = !sftp.eof(sftpHandle: handle)
    }

    success = sftp.closeHandle(sftpHandle: handle)
    if success == false {
        print("\(sftp.lastErrorText!)")
        return
    }

    print("Read \(bd.numBytes.intValue) bytes with no read failures.")

    sftp.disconnect()

}