Using an NSFileHandle, it is pretty easy to remove n number of characters from the end of the file using truncateFileAtOffset.
-(void)removeCharacters:(int)numberOfCharacters fromEndOfFile:(NSFileHandle*)fileHandle {
unsigned long long fileLength = [fileHandle seekToEndOfFile];
[fileHandle truncateFileAtOffset:fileLength - numberOfCharacters];
}
However removing characters from the front of the file doesn't seem possible without having to copy all of the remaining data into memory, overwriting the file and then writing the remaining data back into the file.
-(void)removeCharacters:(int)numberOfCharacters fromBeginningOfFile:(NSFileHandle*)fileHandle {
[fileHandle seekToFileOffset:numberOfCharacters];
NSData *remainingData = [fileHandle readDataToEndOfFile];
[fileHandle truncateFileAtOffset:0];
[fileHandle writeData:remainingData];
}
This code works, but will become a liability with large files. What am I missing?
Ideally I'd like to be able to do replaceCharactersInRange:withData: