Sample code for 30+ languages & platforms
Rust

SFTP Read Text File

See more SFTP Examples

Demonstrates how to open a text file on the SSH server and read text.

Chilkat Rust Downloads

Rust

// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

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

// Set some timeouts, in milliseconds:
sftp.set_connect_timeout_ms(5000);
sftp.set_idle_timeout_ms(15000);

// Connect to the SSH server.  
// The standard SSH port = 22
// The hostname may be a hostname or IP address.
let hostname = "sftp.example.com".to_string();
let port = 22;
if sftp.connect(&hostname, port).is_err() {
    println!("{}", sftp.last_error_text());
    return;
}

// Authenticate with the SSH server.  Chilkat SFTP supports
// both password-based authenication as well as public-key
// authentication.  This example uses password authenication.
if sftp.authenticate_pw("myLogin", "myPassword").is_err() {
    println!("{}", sftp.last_error_text());
    return;
}

// After authenticating, the SFTP subsystem must be initialized:
if sftp.initialize_sftp().is_err() {
    println!("{}", sftp.last_error_text());
    return;
}

// Open a file for reading.
let handle = sftp.open_file("myTest.txt", "readOnly", "openExisting").unwrap_or_default();
if !sftp.last_method_success() {
    println!("{}", sftp.last_error_text());
    return;
}

// Assume the file we are reading contains the following text:
// abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ
// (in ANSI format -- i.e. one byte per char).

// Read 26 bytes:
let mut s_text = String::new();
s_text = sftp.read_file_text(&handle, 26, "ansi").unwrap_or_default();
if !sftp.last_method_success() {
    println!("{}", sftp.last_error_text());
    return;
}

// Should print "abcdefghijklmnopqrstuvwxyz";
println!("{}", s_text);

// Read the next 10 bytes.
s_text = sftp.read_file_text(&handle, 10, "ansi").unwrap_or_default();
if !sftp.last_method_success() {
    println!("{}", sftp.last_error_text());
    return;
}

// Should print "1234567890";
println!("{}", s_text);

// Read the next 26 bytes.
s_text = sftp.read_file_text(&handle, 26, "ansi").unwrap_or_default();
if !sftp.last_method_success() {
    println!("{}", sftp.last_error_text());
    return;
}

// Should print "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
println!("{}", s_text);

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

println!("Success.");