Overwrite Data using NSFileHandle

余生长醉 提交于 2019-12-10 01:28:55

问题


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:


回答1:


After playing around more with NSFileHandle it became clear that insertion without overwriting is impossible.

As explained in: Inserting a string at a specified line in text file using objective c "you can only grow a file at the end; not in the middle."

Here is a slightly more optimized version of the above code:

-(void)removeCharacters:(unsigned long long)numberOfCharacters fromBeginningOfFile:(NSFileHandle*)fileHandle {
    [fileHandle seekToFileOffset:numberOfCharacters];

    NSData *remainingData = [fileHandle readDataToEndOfFile];
    [fileHandle seekToFileOffset:0];
    [fileHandle writeData:remainingData];
    [fileHandle truncateFileAtOffset:remainingData.length];
}

I more involved solution would be to buffer the file into another file in chunks. This would mitigate memory concerns.



来源:https://stackoverflow.com/questions/28620522/overwrite-data-using-nsfilehandle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!