It can happen in two ways. Insertion at the end of file or insertion in the middle of the file. Option 1 Insertion at the end. This is also known as appending a file.
- open the file in append access mode.
- Get the data value for to be inserted in file, from user.
- Write the data in the file
- Repeat set 2 & 3 if there is more data to be inserted (appended)
- Close the file.
Option 2 Inserting in the middle of file
There is no way to insert data in the middle of file. This is a limitation because of OS. To handle such insertions re-writing of file is done.
- Get the data value to to be inserted with its position.
- Open the original file in reading mode.
- Open another (temporary) file for writing in it.
- Start reading original file sequentially, simultaneously writing it in the temporary file.
- This is to be repeated till you reach the position of insertion of new data value.
- Write the new value in temporary file.
- Repeat step 4 for remaining data of original file.
- Delete original file
- Change the name of temporary file to original file.
Code for inserting data in the file with the help of another file
It will be similar to the code used for deletion of content using another file. Here instead of not writing the content add it in the file. An alternative to this is, first read the complete data from file into a list. Modify the list and rewrite the modified list in the file.