Saturday, April 27, 2013

NSFileHandle fileHandleWithStandardError example ios


fileHandleWithStandardError

Returns the file handle associated with the standard error file.
+ (id)fileHandleWithStandardError
Return Value
The shared file handle associated with the standard error file.
Discussion of [NSFileHandle fileHandleWithStandardError]
Conventionally this is a terminal device to which error messages are sent. There is one standard error file handle per process; it is a shared instance.[NSFileHandle fileHandleWithStandardError]
When using this method to create a file handle object, the file handle owns its associated file descriptor and is responsible for closing it.
Example of [NSFileHandle fileHandleWithStandardError]
// Create a file handle for reading an arbitrary file
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:p1];
fh = [NSFileHandle fileHandleForReadingAtPath:@"/dev/srandom"];

// Create a file handle for writing to a file
fh = [NSFileHandle fileHandleForWritingAtPath:p2];
fh = [NSFileHandle fileHandleForWritingAtPath:@"/dev/null"];

// Create commonly used file handles
fh = [NSFileHandle fileHandleWithStandardError];
fh = [NSFileHandle fileHandleWithStandardInput];
fh = [NSFileHanfle fileHandleWithStandardOutput];
fh = [NSFileHandle fileHandleWithNullDevice];

// Write data to a file handle
NSString *str = @"Other Unix boxes";
NSData *data = [str dataUsingEncoding:NSASCIIStringEncoding];
[fh writeData:data];

// Read data from a file handle;
// this could be used for something like % echo "Hello" | ThisApp
fh = [NSFileHandle fileHandleWithStandardInput];

// Read all available data and converting it to a string
NSData *data = [fh availableData];
NSString *str = [NSString stringWithData:data];

// You can also read a specified number of bytes
data = [fh readDataOfLength:400];

// Or you can read up to an end-of-file
data = [fh readDataToEndOfFile];

// And close it when finished
[fh closeFile];