Swift
Swift
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 Swift Downloads
func chilkatTest() {
var success: Bool = false
// 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.
let sftp = CkoSFtp()!
// Connect, authenticate, and initialize the SFTP subsystem.
var port: Int = 22
success = sftp.connect(hostname: "sftp.example.com", port: port)
if success == false {
print("\(sftp.lastErrorText!)")
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.
var password: String? = "mySshPassword"
success = sftp.authenticatePw(login: "mySshLogin", password: password)
if success == false {
print("\(sftp.lastErrorText!)")
return
}
success = sftp.initializeSftp()
if success == false {
print("\(sftp.lastErrorText!)")
return
}
var handle: String? = sftp.openFile(filename: "subdir/data.txt", access: "readOnly", createDisp: "openExisting")
if sftp.lastMethodSuccess == false {
print("\(sftp.lastErrorText!)")
return
}
let bd = CkoBinData()!
var chunkSize: Int = 4096
var reading: Bool = true
while reading {
success = sftp.readFileBd(handle: handle, numBytes: chunkSize, bd: bd)
if sftp.lastReadFailed(sftpHandle: handle) {
print("\(sftp.lastErrorText!)")
return
}
// Report how many bytes the last read actually returned. A normal EOF read reports 0.
var lastCount: Int = sftp.lastReadNumBytes(sftpHandle: handle).intValue
print("Last read returned \(lastCount) bytes.")
reading = !sftp.eof(sftpHandle: handle)
}
success = sftp.closeHandle(sftpHandle: handle)
if success == false {
print("\(sftp.lastErrorText!)")
return
}
print("Total: \(bd.numBytes.intValue) bytes.")
sftp.disconnect()
}