Zig
Zig
Check Whether the Last SFTP Read Failed
See more SFTP Examples
Demonstrates the Chilkat SFtp.LastReadFailed method, which returns whether the most recent read for a handle failed. The only argument is the handle. A normal end-of-file is not a failure.
Background: A chunked read loop needs to tell three outcomes apart: more data, a clean end-of-file, and an actual error such as a dropped connection or a revoked handle.
LastReadFailed isolates the error case — it is false on a normal EOF read (which succeeds with zero bytes) and true for an empty, malformed, or already-closed handle — so the loop can stop cleanly on EOF but bail out with an error message on a genuine failure.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.LastReadFailed method, which returns whether the most recent read for a
// handle failed. The only argument is the handle. A normal end-of-file is NOT a failure.
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;
};
var reading: bool = true;
const chunk_size = 4096;
const bd = try chilkat.BinData.init();
defer bd.deinit();
while (reading) {
try sftp.readFileBd(handle, chunk_size, bd);
// Distinguish an actual read failure from a normal EOF. On EOF the read succeeds, returns
// zero bytes, and LastReadFailed is false.
if (sftp.lastReadFailed(handle)) {
std.debug.print("Read failed: {s}\n", .{try sftp.getLastErrorText(alloc)});
return;
}
reading = !sftp.eof(handle);
}
sftp.closeHandle(handle) catch {
std.debug.print("{s}\n", .{try sftp.getLastErrorText(alloc)});
return;
};
std.debug.print("Read {d} bytes with no read failures.\n", .{bd.getNumBytes()});
sftp.disconnect();
}