Zig
Zig
Get the Byte Count of the Last SFTP Read
See more SFTP Examples
Demonstrates the Chilkat SFtp.LastReadNumBytes method, which returns the number of bytes received by the most recent read for a handle. The only argument is the handle.
Background: SFTP reads may return fewer bytes than requested even before the end of the file, so knowing the actual count is useful for tracking progress and for advancing an explicit offset by the right amount. Both a normal EOF read and a failed read report
0, so pair this with Eof and LastReadFailed to interpret a zero-byte result correctly.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// Demonstrates the SFtp.LastReadNumBytes method, which returns the number of bytes received by
// the most recent read for a handle. 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;
};
const bd = try chilkat.BinData.init();
defer bd.deinit();
const chunk_size = 4096;
var reading: bool = true;
while (reading) {
try sftp.readFileBd(handle, chunk_size, bd);
if (sftp.lastReadFailed(handle)) {
std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
return;
}
// Report how many bytes the last read actually returned. A normal EOF read reports 0.
const last_count = sftp.lastReadNumBytes(handle);
std.debug.print("Last read returned {d} bytes.\n", .{last_count});
reading = !sftp.eof(handle);
}
sftp.closeHandle(handle) catch {
std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
return;
};
std.debug.print("Total: {d} bytes.\n", .{bd.getNumBytes()});
sftp.disconnect();
}