简体   繁体   中英

How do you write to a specific line of a txt file in C?

I would like to overwrite a certain line in a txt file while keeping all others the same. Is there a nice and simple way of doing this?

Basicly use Fseek() to search the sequence of bits that you want to change,
then use Fwrite() to overwrite the old text

OBS: you need to open the file in rw mode to overwrite

fopen ("myfile.txt", "wr");

use those referenses:

http://www.cplusplus.com/reference/cstdio/fwrite/
http://www.cplusplus.com/reference/cstdio/fseek/

(it says C++ but works on C)

Unless the length of the line you are overwriting has the same number of bytes, you can't "insert" or "remove" bytes into or from an existing file. You would have to write a new file:

  1. Read in all the old lines up to the one you need to overwrite, and write them to another output stream (either a new file pointer or stdout )
  2. Write out your new line to the output stream
  3. Read in all the old lines after the line you overwrite, and write those lines to the new output stream

If you want to overwrite existing bytes and you know for sure that the lengths of the old and new lines are exactly equivalent, then you can:

  1. fopen() the file in rw mode
  2. fseek() to the byte position of the old line (or read in characters until you hit some preset number of newline characters, etc. — basically, you want to move the file pointer to the start of the old line)
  3. fwrite() new bytes over the old line's bytes
  4. fclose() the file pointer

If you really need to overwrite bytes in the same file and your new line has fewer bytes than the old line, you could perhaps do some tricks where you overwrite the end of the old line with space characters up to the newline character, but the cleaner solution is to simply write a new file with the updated content.

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