Objective-C
Objective-C
Read Text from a Remote SFTP File (Sequential)
See more SFTP Examples
Demonstrates the Chilkat SFtp.ReadFileText method, which reads up to a number of bytes from the current position of an open handle and decodes them to text. The arguments are the handle, the maximum number of bytes, and the charset. This example reads in chunks until end-of-file.
Background: Reading a file in bounded chunks keeps memory use predictable regardless of file size, which is why the loop reads a fixed amount and repeats until
Eof. A subtlety worth knowing: the byte limit is applied to the encoded bytes, so a chunk boundary could in principle fall in the middle of a multibyte character — accumulating the pieces and decoding the whole avoids any such issue in practice here since the text is reassembled in a StringBuilder.Chilkat Objective-C Downloads
#import <CkoSFtp.h>
#import <NSString.h>
#import <CkoStringBuilder.h>
BOOL success = NO;
// Demonstrates the SFtp.ReadFileText method, which reads up to a number of bytes from the current
// position of an open handle and decodes them to text. The 1st argument is the handle, the 2nd
// is the maximum number of bytes, and the 3rd is the charset.
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;
}
// Open the remote file for reading.
NSString *handle = [sftp OpenFile: @"subdir/notes.txt" access: @"readOnly" createDisp: @"openExisting"];
if (sftp.LastMethodSuccess == NO) {
NSLog(@"%@",sftp.LastErrorText);
return;
}
// Read the file in chunks until end-of-file, accumulating the text.
CkoStringBuilder *sbContent = [[CkoStringBuilder alloc] init];
int chunkSize = 4096;
BOOL reading = YES;
while (reading) {
NSString *chunk = [sftp ReadFileText: handle numBytes: [NSNumber numberWithInt: chunkSize] charset: @"utf-8"];
if ([sftp LastReadFailed: handle]) {
NSLog(@"%@",sftp.LastErrorText);
return;
}
[sbContent Append: chunk];
// Stop once the end of the file has been reached.
reading = ![sftp Eof: handle];
}
success = [sftp CloseHandle: handle];
if (success == NO) {
NSLog(@"%@",sftp.LastErrorText);
return;
}
NSLog(@"%@",[sbContent GetAsString]);
[sftp Disconnect];