Swift
Swift
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 Swift Downloads
func chilkatTest() {
var success: Bool = false
// 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.
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
}
// 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.
let sbContent = CkoStringBuilder()!
var chunkSize: Int = 4096
var reading: Bool = true
while reading {
var chunk: String? = sftp.readFileText(sftpHandle: handle, numBytes: chunkSize, charset: "utf-8")
if sftp.lastReadFailed(sftpHandle: handle) {
print("\(sftp.lastErrorText!)")
return
}
sbContent.append(value: chunk)
reading = !sftp.eof(sftpHandle: handle)
}
success = sftp.closeHandle(sftpHandle: handle)
if success == false {
print("\(sftp.lastErrorText!)")
return
}
print("\(sbContent.getAsString()!)")
sftp.disconnect()
}