Saturday, April 27, 2013

NSFileHandle offsetInFile example ios


offsetInFile

Returns the position of the file pointer within the file represented by the receiver.
- (unsigned long long)offsetInFile
Return Value
The position of the file pointer within the file represented by the receiver.
Special Considerations on [NSFileHandle offsetInFile]
Raises an exception if the message is sent to a file handle representing a pipe or socket or if the file descriptor is closed.
Example of [NSFileHandle offsetInFile]

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];