Sample code for 30+ languages & platforms
Zig

Open a Remote Directory on an SFTP Server

See more SFTP Examples

Demonstrates the Chilkat SFtp.OpenDir method, which opens a remote directory and returns a handle for reading its entries. The only argument is the directory path. Close the handle with CloseHandle when finished.

Background: Listing a directory in SFTP is a handle-based operation, mirroring file access: open the directory to get a handle, read its entries, then close it. The handle is passed to ReadDirListing to retrieve the names and attributes. As with file handles, the directory handle is a server-side resource that should be closed to avoid exhausting the server's limits.

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 SFtp.OpenDir method, which opens a remote directory and returns a handle for
    // reading its entries.  The only argument is the directory path.

    const sftp = try chilkat.SFtp.init();
    defer sftp.deinit();

    // Connect, authenticate, and initialize the SFTP subsystem.
    const port = 22;
    sftp.connect("sftp.example.com", port) catch {
        std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
        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.
    const password = "mySshPassword";

    sftp.authenticatePw("mySshLogin", password) catch {
        std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
        return;
    };

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

    // Open the remote directory.  OpenDir returns a handle string.
    const handle = sftp.openDir(alloc, "subdir") catch {
        std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Opened directory, handle = {s}\n", .{handle});

    // The directory entries are read with ReadDirListing using this handle.

    // Close the handle when finished.
    sftp.closeHandle(handle) catch {
        std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
        return;
    };

    sftp.disconnect();
}