Saturday, April 27, 2013

NSFileHandle readDataOfLength example ios


readDataOfLength:

Synchronously reads data up to the specified number of bytes.
- (NSData *)readDataOfLength:(NSUInteger)length
Parameters
length
The number of bytes to read from the receiver.
Return Value of [NSFileHandle readDataOfLength]
The data available through the receiver up to a maximum of length bytes, or the maximum size that can be represented by an NSData object, whichever is the smaller.
Discussion of [NSFileHandle readDataOfLength]
If the receiver is a file, this method returns the data obtained by reading length bytes starting at the current file pointer. If length bytes are not available, this method returns the data from the current file pointer to the end of the file. If the receiver is a communications channel, the method reads up to length bytes from the channel. Returns an empty NSDataobject if the file is positioned at the end of the file or if an end-of-file indicator is returned on a communications channel. This method raises NSFileHandleOperationException if attempts to determine the file-handle type fail or if attempts to read from the file or channel fail.
Example of [NSFileHandle readDataOfLength]
NSString *testFile = @"/test.txt";
NSFileHandle * file = [NSFileHandle fileHandleForWritingAtPath:testFile];
[file seekToEndOfFile];
[file seekToFileOffset:30];
NSLog(@"offset : %llu", [file offsetInFile]);
[file closeFile];  

Read from file
NSString *testFile = @"/test.txt";
NSFileHandle * file = [NSFileHandle fileHandleForWritingAtPath:testFile];
[file seekToFileOffset:30];
NSLog(@"offset : %llu", [file offsetInFile]);

NSData *databuffer = [file readDataOfLength:10];

[file closeFile];  

 Write to file.
NSString *testFile = @"/test.txt";
NSFileHandle * file = [NSFileHandle fileHandleForWritingAtPath:testFile];
[file seekToFileOffset:30];
NSLog(@"offset : %llu", [file offsetInFile]);

NSData *databuffer = [file readDataOfLength:10];
[file seekToFileOffset:50];
[file writeData:databuffer];

[file closeFile];