Search code examples
cindexingfile-handling

How to write a line to a file at a given line index in C?


recently, I have a problem with indexing a line in a file in C. For example I have the following poem written (By ChatGPT) in a text file:

In lands where ice once reigned supreme,
Now melts away, a silent scream.
Glaciers weep in rivers wide,
Their tears a warning, a rising tide.

Oceans swell with fevered heat,
As warming waters gently beat.
Their fading colors tell a tale.

Now I want to add this line Coral reefs, once vibrant, now pale, to the 6th index:

...
As warming waters gently beat.
                                 <-- here
Their fading colors tell a tale.

How do I do it easily with C? Is there a function to achieve this task? Thanks.


Solution

  • How do I do it easily with C?

    It takes a bit of code.

    Is there a function to achieve this task?

    No.


    Use lots of error checking.

    1. Read the original file "src" and copy it to a new file "tmp" up to the Nth line.

    2. Append your new line to the new file.

    3. Continue reading the original file "src" and append the rest of it to the new file "tmp".

    4. Close new file "tmp".

    5. Rename "src" to "src.bak"

    6. Rename "tmp" to "src"

    7. If all is successful, delete "src.bak" if desired.