仅覆盖文件的特定部分
我知道这是问过一次,但是我不明白答案。
假设我有一个这样的文件:
Guest list:
jon
mary
paul
luke
Table list:
然后,例如,我想更改客人的姓名。我知道我需要搜索字符串“来宾列表”,然后覆盖“来宾列表”和“餐桌列表”之间的所有内容。但我不知道该怎么做。
我正在使用 C++,并且我更喜欢使用 fstream :D
谢谢!
编辑:
对于相对较小的文件来说,编写一个全新的文件似乎是最好的方法。我可能会使用这种方法来完成我现在想做的事情。但我仍然对如何处理需要更新大文件的情况很感兴趣。
I know this was asked once, but I didn't understand the answer.
Let's say I have a file like this:
Guest list:
jon
mary
paul
luke
Table list:
And then, for example, I want to change the names of the guests. I understood that I need to search for the string "Guest list" and then overwrite everything between "Guest list" and "Table list". But I have no idea how to do that.
I'm using C++, and I prefer using fstream :D
Thanks !
edit:
It seems that writing a completely new file is the best method with relatively small files. I'll probably use this method for what I want to do now. But I'm still really interested in how to handle situations where you need to update a huge file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果新来宾名称与旧来宾名称的长度不完全匹配,则无法就地执行替换,最好使用临时文件。
If the new guest names do not match exactly the length of the old guest names, you can't perform the replacement in-place, it's best to use a temporary file.
如果您可以将整个文件放入内存中(正如 Space 所指出的),请使用
ifstream
读取它,并使用ofstream
写出“Guest List”线,以及所有新名称。这不是唯一的方法,但却是最方便的。If you can fit the entire file in memory (as Space had pointed out), read it in using an
ifstream
, and, using anofstream
write out the "Guest List" line, and all of the new names. It's not the only way, but it's the most convenient.因此,这里有一些代码(此类问题并不像乍一看那么简单):
由于此示例使用
std::list
,因此迭代器guest_list_end
即使我们添加或删除客人,代码>仍然有效。请记住,列表上的find
和remove
具有线性复杂度,因此如果文件很长,这可能会很昂贵。此代码还假设客人后面跟着餐桌列表。如果情况发生变化,您必须修改
find
语句。So, here is some code (these kinds of problems are not as simple as they seem at first glance):
Since you this example uses an
std::list
, the the iteratorguest_list_end
remains valid, even when we add or remove guests. Keep in mind thatfind
andremove
on lists have linear complexity, so if the file is long, this might be costly.This code also assumes that the guest is followed by the table list. If that changes, you have to modify the
find
-statement.