detraveller
detraveller

Reputation: 295

How to write on a specific line in a file?

I want to write some data on an already existing file. It is a file that contains about 8-10 lines of header(# comments) and then thousands of lines of data values. What i want is to keep the header same but add the updated data values to the file. It is quite possible that after the update I have less number of lines of data values.

So basically i want to erase everything after the last # comment in the header and then start writing the new values from there onwards. Is that possible?

Here is an example:

Original File

#Program
#Date
#Hello
0 23 23 54
1 12 4 2
2 253 786 9887
3 3 23 54
4 1 4 4
5 23 6 81

Updated File

#Program
#Date
#Hello
0 2 23 54
2 253 786 9887
5 23 6 81

The code i am editing is using fopen to read the file and fprintf to write to it. I would prefer if the answers are along these lines so that i don't have to change those two.

Upvotes: 0

Views: 1378

Answers (2)

Eric
Eric

Reputation: 19873

Write a function that reads the headers from the file and store them into a class/variable/struct.

Write a function that writes the headers to the file

Write a function that writes the desired values to the file

Execute all three functions in that order. The fact that it is the same file that you overwrite is irrelevant, just be sure to close it before writing back to it

Upvotes: 2

GuLearn
GuLearn

Reputation: 1864

The simplest way I came up with is open the Original File, read and copy the header in to memory such as a string header. Then overwrite the whole file by writing the header, then the new data

Upvotes: 6

Related Questions