替换文件中的一行

发布于 2024-09-18 21:29:48 字数 205 浏览 3 评论 0原文

我有一个非常大的文本文件,我的 iPad 程序需要偶尔替换一行数据(换行符:'\n')。我怎样才能有效地做到这一点?一次写入整个文件不是一种选择。

我一直在研究 NSFileHandle,看起来它会做我想要的事情;现在我无法弄清楚如何找到 X 行,然后用字符串中的数据替换它。我想完成之后,我需要做的就是调用synchronizeFile,对吗?

我感谢你的帮助!

I have a very large text file, and my iPad program needs to occasionally replace a single line of data (newline: '\n'). How can I do this efficiently? Writing the entire file at once is not an option.

I've been looking into NSFileHandle, and it looks like it will do what I want; right now I'm having trouble figuring out how to find line X, and then replace it with the data from a string. I think after that's done, all I need to do is call synchronizeFile, right?

I appreciate your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月朦胧 2024-09-25 21:29:48

如果不写入整个文件,您就无法真正做到这一点。您可以查找行的开头,然后写入新行。但首先你必须找出该线的偏移量。如果您还没有,这意味着从头读取文件到该行。然后您可以编写新行,但前提是它的长度与原始行完全相同。如果它更长,它将覆盖下一行 - 无法将数据插入文件中。如果新行比旧行短,则旧行的末尾将保留。同样的长度要求也很棘手。这意味着相同的字节长度。根据字符编码的不同,某些字符可能需要比其他字符更多的字节。

如果您确实需要执行此操作并使其适用于每种情况,则必须使用以下步骤:

  1. 读取整个文件以找出您感兴趣的行的偏移​​量
  2. 查找该行的偏移
  3. 量 写入new line
  4. 写出您在步骤 1 中读取的文件的其余部分。

无论行多长或多短或如何编码,该算法都将起作用。但这可能比只写出整个文件更昂贵,特别是如果你已经将它存储在内存中的话。

您是否确实验证过写出整个文件是不可接受的,或者您是否在这里进行了过早的优化?如果您的文本文件确实那么大,您应该考虑使用数据库,例如 SQLite,或者使用 Core Data。

You cannot really do this without writing the whole file. You could seek to the beginning of the line and then write the new line. But first you’d have to find out the offset of that line. If you don’t already have that this means reading the file from the beginning to that line. Then you could write the new line, but only if it is exactly the same length as the original line. If it is longer it will overwrite the next line - there is no way to insert data into a file. If the new line is shorter than the old one the end of the old line will remain. The same length requirement is also tricky. This means the same length in bytes. Depending on the character encoding some characters might require more bytes than others.

If you really need to do this and have it work for about every case you’d have to use those steps:

  1. Read the entire file to find out the offset of the line you’re interested in
  2. Seek to the offset of the line
  3. Write the new line
  4. Write out the rest of the file you read in step 1.

This algorithm will work, no matter how long or short the lines are or how they are encoded. But this will probably be more expensive than just writing out the whole file, especially if you have it in memory anyways.

Have you actually verified that it is not acceptable to write out the whole file or are you doing premature optimization here? If your text file is really that big you should be considering a database, like SQLite, or to use Core Data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文