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:
stdout
) 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:
fopen()
the file in rw
mode 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) fwrite()
new bytes over the old line's bytes 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.