Sample code for 30+ languages & platforms
Zig

SFTP Read Text File

See more SFTP Examples

Demonstrates how to open a text file on the SSH server and read text.

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 assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

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

    // Set some timeouts, in milliseconds:
    sftp.setConnectTimeoutMs(5000);
    sftp.setIdleTimeoutMs(15000);

    // Connect to the SSH server.
    // The standard SSH port = 22
    // The hostname may be a hostname or IP address.
    const hostname = "sftp.example.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 file for reading.
    const handle = sftp.openFile(alloc, "myTest.txt", "readOnly", "openExisting") catch {
        std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
        return;
    };

    // Assume the file we are reading contains the following text:
    // abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ
    // (in ANSI format -- i.e. one byte per char).

    // Read 26 bytes:
    var s_text: [:0]const u8 = "";
    s_text = sftp.readFileText(alloc, handle, 26, "ansi") catch {
        std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
        return;
    };

    // Should print "abcdefghijklmnopqrstuvwxyz";
    std.debug.print("{s}\n", .{s_text});

    // Read the next 10 bytes.
    s_text = sftp.readFileText(alloc, handle, 10, "ansi") catch {
        std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
        return;
    };

    // Should print "1234567890";
    std.debug.print("{s}\n", .{s_text});

    // Read the next 26 bytes.
    s_text = sftp.readFileText(alloc, handle, 26, "ansi") catch {
        std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
        return;
    };

    // Should print "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    std.debug.print("{s}\n", .{s_text});

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

    std.debug.print("Success.\n", .{});
}