简体   繁体   English

一种覆盖文件中几个位置的方法

[英]A way to overwrite few positions in file

I correctly read values from some positions in my file, but I'm getting problem when I need to rewrite those values. 我从文件中的某些位置正确读取了值,但是当我需要重写这些值时遇到了问题。 It all messes up in file, after what my file reader doesn't find what he needs at required positions. 在我的文件阅读器找不到所需位置后,所有这些都被文件弄乱了。 Is there some way to overwrite the whole line, and to avoid these situations? 有什么方法可以覆盖整个行并避免这些情况吗? I am using lseek() function to move file pointer to position I need. 我正在使用lseek()函数将文件指针移动到所需的位置。

Since you say "line", I assume you're talking about text files. 由于您说的是“行”,因此我假设您是在谈论文本文件。

In that case: no, there's no way to overwrite a single line, except if the new line you want to write is exactly the same length. 在这种情况下:否,没有办法覆盖一行, 除非您要写入的新行的长度完全相同

This is because the file abstraction on disk doesn't work like editing a file in eg a text editor, you can't do insert/delete in the middle without re-writing all the trailing data after the point of the change. 这是因为磁盘上的文件抽象不能像在文本编辑器中编辑文件那样工作,如果没有更改点之后的所有尾随数据,则不能在中间插入/删除。

In general you need to construct the change in memory and overwrite the entire file (or at least the part starting with the change). 通常,您需要构造内存中的更改并覆盖整个文件(或至少覆盖更改开始的部分)。

You can 您可以

  1. read the tail after the line to change, and write it back together with the change, or 读取要更改的行后的尾巴,并将其与更改一起写回,或者
  2. resort to memory mapped files: you do the change like you'd do with C-strings, and the OS takes care of the rest. 诉诸于内存映射文件:您像使用C字符串那样进行更改,其余部分由操作系统处理。

I'd prefer the memory mapped file. 我希望使用内存映射文件。 When portability is an issue, boost has a portable abstraction for them. 当可移植性成为一个问题时,boost为其提供了可移植的抽象。 I'd consider that before resorting to variant 1. 在采用变体1之前,我会考虑这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM