Sample code for 30+ languages & platforms
Tcl

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

Tcl

load ./chilkat.dll

set success 0

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

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
}

#  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.
set sbContent [new_CkStringBuilder]

set chunkSize 4096
set reading 1
while {$reading} {
    set chunk [CkSFtp_readFileText $sftp $handle $chunkSize "utf-8"]
    if {CkSFtp_LastReadFailed $sftp $handle} then {
        puts [CkSFtp_lastErrorText $sftp]
        delete_CkSFtp $sftp
        delete_CkStringBuilder $sbContent
        exit
    }

    CkStringBuilder_Append $sbContent $chunk
    set reading ![CkSFtp_Eof $sftp $handle]
}

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

puts [CkStringBuilder_getAsString $sbContent]

CkSFtp_Disconnect $sftp

delete_CkSFtp $sftp
delete_CkStringBuilder $sbContent