M
M
Monile2021-11-03 22:06:05
C++ / C#
Monile, 2021-11-03 22:06:05

How to edit a specific line in a file?

The console enters the line number that needs to be edited, I found it in the file, but how can I now replace the data and save it to a file?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2021-11-04
@wataru

You will have to read the entire file, count the required number of lines, then replace the piece between two newlines with the edited value, and finally rewrite the entire file. You can optimize a little and rewrite not the entire file, but only starting from the changed line. Use fseek to move to the beginning of the line/file, fwrite to write new data, and ftruncate to truncate the file if it gets shorter.

M
Monile, 2021-11-04
@Monile

I originally had a structure and it has an id. The console asked for the number of the line that I would like to replace, then I looked for this id in the structure and changed all its values ​​to new ones, and then overwrote the file. Through fseek with fwrite I tried, but something didn’t work out for me, most likely I did something wrong.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question