Sample code for 30+ languages & platforms
Rust

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

Rust

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

let sftp = chilkat::SFtp::new();

// Connect, authenticate, and initialize the SFTP subsystem.
let port = 22;
if sftp.connect("sftp.example.com", port).is_err() {
    println!("{}", sftp.last_error_text());
    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.
let password = "mySshPassword".to_string();

if sftp.authenticate_pw("mySshLogin", &password).is_err() {
    println!("{}", sftp.last_error_text());
    return;
}

if sftp.initialize_sftp().is_err() {
    println!("{}", sftp.last_error_text());
    return;
}

let Ok(handle) = sftp.open_file("subdir/data.txt", "readOnly", "openExisting") else {
    println!("{}", sftp.last_error_text());
    return;
};

// 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.
let sb_content = chilkat::StringBuilder::new();
let chunk_size = 4096;
let mut reading = true;
while reading {
    let chunk = sftp.read_file_text(&handle, chunk_size, "utf-8").unwrap_or_default();
    if sftp.last_read_failed(&handle) {
        println!("{}", sftp.last_error_text());
        return;
    }

    let _ = sb_content.append(&chunk);
    reading = !sftp.eof(&handle);
}

if sftp.close_handle(&handle).is_err() {
    println!("{}", sftp.last_error_text());
    return;
}

println!("{}", sb_content.get_as_string().unwrap_or_default());

sftp.disconnect();