Saturday, April 27, 2013

NSFileHandle truncateFileAtOffset example ios


truncateFileAtOffset:

Truncates or extends the file represented by the receiver to a specified offset within the file and puts the file pointer at that position.
- (void)truncateFileAtOffset:(unsigned long long)offset
Parameters
offset
The offset within the file that will mark the new end of the file.
Discussion of [NSFileHandle truncateFileAtOffset]
If the file is extended (if offset is beyond the current end of file), the added characters are null bytes.
Example of [NSFileHandle truncateFileAtOffset]

// get path to Documents/somefile.txt
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"somefile.txt"];

// create if needed
if (![[NSFileManager defaultManager] fileExistsAtPath:path]){
    [[NSData data] writeToFile:path atomically:YES];
} 

// append
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:path];
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
[handle writeData:[@"line of text\n" dataUsingEncoding:NSUTF8StringEncoding]];