user2158031
user2158031

Reputation: 81

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

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 a new ID. My job is to make the program write the new ID into the .txt file without totally overwriting all the information. Say the user wanted to insert the new ID after 267. The user tells me new ID is 123, 12.34, N, 12. The .txt file would have to look like this:

112 12.50 Y 15

267 7.75 N 20

123 12.34 N 12

382 15.50 N 45

Upvotes: 0

Views: 192

Answers (3)

Alexey Frunze
Alexey Frunze

Reputation: 62058

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.

Upvotes: 3

Aniket Inge
Aniket Inge

Reputation: 25705

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!

Upvotes: 2

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70939

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.

Upvotes: 2

Related Questions