Zig Requires Chilkat v11.0.0+
Zig
SFTP Read Directory Listing
See more SFTP Examples
Demonstrates how to download a directory listing and iterate over the files.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Important: It is helpful to send the contents of the
// sftp.LastErrorText property when requesting support.
const sftp = try chilkat.SFtp.init();
defer sftp.deinit();
// Set some timeouts, in milliseconds:
sftp.setConnectTimeoutMs(5000);
sftp.setIdleTimeoutMs(10000);
// Connect to the SSH server.
// The standard SSH port = 22
// The hostname may be a hostname or IP address.
const hostname = "www.my-sftp-server.com";
const port = 22;
sftp.connect(hostname, port) catch {
std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
return;
};
// Authenticate with the SSH server. Chilkat SFTP supports
// both password-based authenication as well as public-key
// authentication. This example uses password authenication.
sftp.authenticatePw("myLogin", "myPassword") catch {
std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
return;
};
// After authenticating, the SFTP subsystem must be initialized:
sftp.initializeSftp() catch {
std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
return;
};
// Open a directory on the server...
// Paths starting with a slash are "absolute", and are relative
// to the root of the file system. Names starting with any other
// character are relative to the user's default directory (home directory).
// A path component of ".." refers to the parent directory,
// and "." refers to the current directory.
const handle = sftp.openDir(alloc, ".") catch {
std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
return;
};
// Download the directory listing:
const dir_listing = try chilkat.SFtpDir.init();
defer dir_listing.deinit();
sftp.readDirListing(handle, dir_listing) catch {
std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
return;
};
// Close the handle for the directory listing.
sftp.closeHandle(handle) catch {
std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
return;
};
// Iterate over the files.
const file_obj = try chilkat.SFtpFile.init();
defer file_obj.deinit();
var i: i32 = 0;
const n = dir_listing.getNumFilesAndDirs();
while (i < n) {
dir_listing.fileAt(i, file_obj) catch {
std.debug.print("{s}\n", .{try dir_listing.getLastErrorText(alloc)});
return;
};
std.debug.print("{s}\n", .{try file_obj.getFilename(alloc)});
std.debug.print("{s}\n", .{try file_obj.getFileType(alloc)});
std.debug.print("Size in bytes: {d}\n", .{file_obj.getSize32()});
std.debug.print("----\n", .{});
i = i + 1;
}
std.debug.print("Success.\n", .{});
}