在C ++中删除一行中的一行 [英] Delete a line in an ofstream in C++

查看:296
本文介绍了在C ++中删除一行中的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要删除文件中的行。我知道你可以存储文件的内容(例如在向量中),擦除该行,然后再次写入。

I want to erase lines within a file. I know you can store the content of the file (in a vector for example), erase the line and write again. However, it feels very cumbersome, and not very efficient if the file gets bigger.

任何人都知道更好,更高效,更优雅的方式吗?

Anyone knows of a better, more efficient, more elegant way of doing it?

推荐答案

磁盘文件没有什么特别的神奇。他们仍然喜欢将数据存储在连续区域(通常称为块)。他们没有办法在这些区域的中间留下无数据的洞。所以如果你想从这些区域的中间删除三个字节,某些地方将通过将该区域中的所有其他内容移回三个字节来完成此任务。不,效率不高。

There's nothing particularly magical about disk files. They still like to store their data in contiguous areas (typically called something like "blocks"). They don't have ways of leaving data-free holes in the middle of these areas. So if you want to "remove" three bytes from the middle of one of these areas, something somewhere is going to have to accomplish this by moving everything else in that area back by three bytes. No, it is not efficient.

这就是为什么文本编辑器(必须做这种事情很多)倾向于加载尽可能多的文件如果不是全部)到RAM中,其中移动数据的速度要快得多。它们通常只在请求(或定期)时将更改写回磁盘。如果你要做很多这样的变化,我建议从他们的书上做一个页面,并做类似的事情。

This is why text editors (which have to do this kind of thing a lot) tend to load as much of the file as possible (if not all of it) into RAM, where moving data around is much faster. They typically only write changes back to disk when requested (or periodically). If you are going to have to make lots of changes like this, I'd suggest taking a page from their book and doing something similar.

这篇关于在C ++中删除一行中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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