Sample code for 30+ languages & platforms
Rust

Count Files in a Remote FTP Directory

See more FTP Examples

Demonstrates the Chilkat Ftp2.GetDirCount method, which returns the number of files and directories in the current remote directory. It takes no arguments; the first call retrieves the listing, and the count reflects the case-insensitive ListPattern filter. A negative return indicates failure.

Background: GetDirCount is the entry point to Chilkat's index-based directory API: its first call fetches the listing for the current directory into a cache, and the returned count establishes the valid index range (0 through count - 1) for the accessor methods that read names, sizes, and attributes. The ListPattern property narrows the listing to matching names before counting, which is how you list, say, only *.html without filtering in your own code.

Chilkat Rust Downloads

Rust

// Demonstrates the Ftp2.GetDirCount method, which returns the number of files and directories in
// the current remote directory's listing.  It takes no arguments.  The first call retrieves the
// listing; the count reflects the case-insensitive ListPattern filter.

let ftp = chilkat::Ftp2::new();

ftp.set_hostname("ftp.example.com");
ftp.set_username("myFtpLogin");

// 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.
ftp.set_password("myPassword");

if ftp.connect().is_err() {
    println!("{}", ftp.last_error_text());
    return;
}

if ftp.change_remote_dir("public_html").is_err() {
    println!("{}", ftp.last_error_text());
    return;
}

// Optionally filter the listing with a wildcard pattern.  "*" (the default) matches everything.
ftp.set_list_pattern("*.html");

let n = ftp.get_dir_count();
if n < 0 {
    println!("{}", ftp.last_error_text());
    return;
}

println!("Matching entries: {}", n);

// The count defines the valid index range 0 through n-1 for the indexed accessor methods.
for i in 0..n {
    let name = ftp.get_filename(i).unwrap_or_default();
    println!("{}", name);
}

if ftp.disconnect().is_err() {
    println!("{}", ftp.last_error_text());
    return;
}