Sample code for 30+ languages & platforms
Objective-C

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 Objective-C Downloads

Objective-C
#import <CkoSFtp.h>
#import <NSString.h>
#import <CkoBinData.h>

BOOL success = NO;

//  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.

CkoSFtp *sftp = [[CkoSFtp alloc] init];

//  Connect, authenticate, and initialize the SFTP subsystem.
int port = 22;
success = [sftp Connect: @"sftp.example.com" port: [NSNumber numberWithInt: port]];
if (success == NO) {
    NSLog(@"%@",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.
NSString *password = @"mySshPassword";

success = [sftp AuthenticatePw: @"mySshLogin" password: password];
if (success == NO) {
    NSLog(@"%@",sftp.LastErrorText);
    return;
}

success = [sftp InitializeSftp];
if (success == NO) {
    NSLog(@"%@",sftp.LastErrorText);
    return;
}

NSString *handle = [sftp OpenFile: @"subdir/data.txt" access: @"readOnly" createDisp: @"openExisting"];
if (sftp.LastMethodSuccess == NO) {
    NSLog(@"%@",sftp.LastErrorText);
    return;
}

BOOL reading = YES;
int chunkSize = 4096;
CkoBinData *bd = [[CkoBinData alloc] init];
while (reading) {
    success = [sftp ReadFileBd: handle numBytes: [NSNumber numberWithInt: chunkSize] bd: 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]) {
        NSLog(@"%@%@",@"Read failed: ",sftp.LastErrorText);
        return;
    }

    reading = ![sftp Eof: handle];
}

success = [sftp CloseHandle: handle];
if (success == NO) {
    NSLog(@"%@",sftp.LastErrorText);
    return;
}

NSLog(@"%@%d%@",@"Read ",[bd.NumBytes intValue],@" bytes with no read failures.");

[sftp Disconnect];