Sample code for 30+ languages & platforms
Zig

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

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

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

    const ftp = try chilkat.Ftp2.init();
    defer ftp.deinit();

    ftp.setHostname("ftp.example.com");
    ftp.setUsername("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.setPassword("myPassword");

    ftp.connect() catch {
        std.debug.print("{s}\n", .{try ftp.getLastErrorText(alloc)});
        return;
    };

    ftp.changeRemoteDir("public_html") catch {
        std.debug.print("{s}\n", .{try ftp.getLastErrorText(alloc)});
        return;
    };

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

    const n = ftp.getDirCount();
    if (n < 0) {
        std.debug.print("{s}\n", .{try ftp.getLastErrorText(alloc)});
        return;
    }

    std.debug.print("Matching entries: {d}\n", .{n});

    // The count defines the valid index range 0 through n-1 for the indexed accessor methods.
    var i: i32 = 0;
    i = 0;
    while (i < n) : (i += 1) {
        const name = try ftp.getFilename(alloc, i);
        std.debug.print("{s}\n", .{name});
    }

    ftp.disconnect() catch {
        std.debug.print("{s}\n", .{try ftp.getLastErrorText(alloc)});
        return;
    };
}