Appending text information to a text file at a certain spot without overwriting old information (C)

后端 未结 3 1049
感动是毒
感动是毒 2020-12-22 09:29

So I have a txt file that looks like this:

112 12.50 Y 15

267 7.75 N 20

382 15.50 N 45

User is prompted where he wants to insert

相关标签:
3条回答
  • 2020-12-22 09:45

    The only option that you have to add information in the middle of a file without overwriting old data is to move manually all the data following the position where you want to add into the file.

    0 讨论(0)
  • 2020-12-22 09:52

    In standard C there's no functionality to insert new data at a certain location within a file.

    The only two options in plain C are:

    1. Create a temporary file, copy the old file's data up to the insertion point to the temp file, write the new data to the temp file, copy the rest of the old file's data to the temp file, rename the temp file to the old file's name.
    2. Figure out how much new data needs to be inserted, move (by copying) all data from the insertion point by that amount, write the new data at the insertion point.

    There may be OS-specific functions to perform insertion of data at an arbitrary location within a file. But, again, not in the standard C library as defined by the C standard.

    0 讨论(0)
  • 2020-12-22 09:53

    steps:

    1. Create a temporary file
    2. Read each line from the source file and write to temporary file, parsing it as you go
    3. Then insert the new line after you've found the ID after which you would want the new line to be inserted
    4. write all the remaining lines from the source file
    5. delete the source file
    6. rename the temporary file to the name of the source file.
    7. celebrate!
    0 讨论(0)
提交回复
热议问题