ls in Cocoa

//Launch “ls -l -a -t” in the current directory, and then read the result into an NSString:

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @”/bin/ls”];

NSArray *arguments;
arguments = [NSArray arrayWithObjects: @”-l”, @”-a”, @”-t”, nil];
[task setArguments: arguments];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];

NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@”got\n%@”, string);

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.