Sample code for 30+ languages & platforms
Zig

Detect End-of-File on a Remote SFTP File

See more SFTP Examples

Demonstrates the Chilkat SFtp.Eof method, which returns whether the most recent read for a handle received the SFTP end-of-file status. The only argument is the handle. This example reads until Eof is true.

Background: The timing here is worth understanding: reading exactly through the final byte does not immediately set EOF. The next read succeeds, returns zero bytes, sets the status to SSH_FX_EOF, and only then does Eof report true. That is why the loop tests Eof after each read rather than assuming a short read means the end — a short read can also just be the server returning less than requested.

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.Eof method, which returns whether the most recent read for a handle
    // received the SFTP end-of-file status.  The only argument is the handle.

    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;
    };

    const handle = sftp.openFile(alloc, "subdir/data.txt", "readOnly", "openExisting") catch {
        std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
        return;
    };

    // Read until Eof reports the end of the file.  Note that reading exactly through the final byte
    // does not set EOF; the next read returns zero bytes and then Eof becomes true.
    const sb_content = try chilkat.StringBuilder.init();
    defer sb_content.deinit();
    const chunk_size = 4096;
    var reading: bool = true;
    while (reading) {
        const chunk = try sftp.readFileText(alloc, handle, chunk_size, "utf-8");
        if (sftp.lastReadFailed(handle)) {
            std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
            return;
        }

        sb_content.append(chunk) catch {};
        reading = !sftp.eof(handle);
    }

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

    std.debug.print("{s}\n", .{try sb_content.getAsString(alloc)});

    sftp.disconnect();
}