使用NSFileHandle覆盖数据 [英] Overwrite Data using NSFileHandle

查看:352
本文介绍了使用NSFileHandle覆盖数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用NSFileHandle,使用truncateFileAtOffset从文件末尾删除n个字符非常容易。

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?

理想情况下,我希望能够做replaceCharactersInRange:withData:

Ideally I'd like to be able to do replaceCharactersInRange:withData:

推荐答案

在使用NSFileHandle进行更多游戏后,很明显无法覆盖插入是不可能的。

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

如下所述:使用目标c在文本文件中的指定行插入一个字符串 你最后只能成长一个文件;而不是在中间。

这是上述代码稍微优化一点的版本:

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.

这篇关于使用NSFileHandle覆盖数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆