简体   繁体   中英

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.

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.

I'd prefer the memory mapped file. When portability is an issue, boost has a portable abstraction for them. I'd consider that before resorting to variant 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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