Sample code for 30+ languages & platforms
Tcl

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

Tcl

load ./chilkat.dll

set success 0

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

set sftp [new_CkSFtp]

#  Connect, authenticate, and initialize the SFTP subsystem.
set port 22
set success [CkSFtp_Connect $sftp "sftp.example.com" $port]
if {$success == 0} then {
    puts [CkSFtp_lastErrorText $sftp]
    delete_CkSFtp $sftp
    exit
}

#  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.
set password "mySshPassword"

set success [CkSFtp_AuthenticatePw $sftp "mySshLogin" $password]
if {$success == 0} then {
    puts [CkSFtp_lastErrorText $sftp]
    delete_CkSFtp $sftp
    exit
}

set success [CkSFtp_InitializeSftp $sftp]
if {$success == 0} then {
    puts [CkSFtp_lastErrorText $sftp]
    delete_CkSFtp $sftp
    exit
}

set handle [CkSFtp_openFile $sftp "subdir/data.txt" "readOnly" "openExisting"]
if {[CkSFtp_get_LastMethodSuccess $sftp] == 0} then {
    puts [CkSFtp_lastErrorText $sftp]
    delete_CkSFtp $sftp
    exit
}

set reading 1
set chunkSize 4096
set bd [new_CkBinData]

while {$reading} {
    set success [CkSFtp_ReadFileBd $sftp $handle $chunkSize $bd]

    #  Distinguish an actual read failure from a normal EOF.  On EOF the read succeeds, returns
    #  zero bytes, and LastReadFailed is 0.
    if {CkSFtp_LastReadFailed $sftp $handle} then {
        puts "Read failed: [CkSFtp_lastErrorText $sftp]"
        delete_CkSFtp $sftp
        delete_CkBinData $bd
        exit
    }

    set reading ![CkSFtp_Eof $sftp $handle]
}

set success [CkSFtp_CloseHandle $sftp $handle]
if {$success == 0} then {
    puts [CkSFtp_lastErrorText $sftp]
    delete_CkSFtp $sftp
    delete_CkBinData $bd
    exit
}

puts "Read [CkBinData_get_NumBytes $bd] bytes with no read failures."

CkSFtp_Disconnect $sftp

delete_CkSFtp $sftp
delete_CkBinData $bd