Sample code for 30+ languages & platforms
Zig

FTP Iterate over Files in Directory Matching ListPattern

See more RSA Examples

Uses the ListPattern property to iterate over the files in a directory matching the pattern.

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();

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

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

    ftp.setHostname("ftp.example.com");
    ftp.setUsername("my_login");
    ftp.setPassword("my_password");
    ftp.setPort(21);
    ftp.setAuthTls(true);

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

    // Change to the "images" sub-directory located under our FTP account's home directory.
    ftp.changeRemoteDir("images") catch {
        std.debug.print("{s}\n", .{try ftp.getLastErrorText(alloc)});
        return;
    };

    ftp.setListPattern("*.png");

    // Fetch the current remote directory contents by calling GetDirCount
    const n = ftp.getDirCount();
    if (n < 0) {
        std.debug.print("{s}\n", .{try ftp.getLastErrorText(alloc)});
        return;
    }

    var i: i32 = 0;
    var filename: [:0]const u8 = "";
    const sb_local_path = try chilkat.StringBuilder.init();
    defer sb_local_path.deinit();

    while (i < n) {
        filename = try ftp.getFilename(alloc, i);
        std.debug.print("{s}\n", .{filename});

        // Download this file.
        sb_local_path.setString("qa_output/") catch {};
        sb_local_path.append(filename) catch {};
        ftp.getFile(filename, try sb_local_path.getAsString(alloc)) catch {
            std.debug.print("{s}\n", .{try ftp.getLastErrorText(alloc)});
            return;
        };

        i = i + 1;
    }
}