Inserting data in a file

Home/Inserting data in a file
Inserting data in a file 2018-03-19T11:36:55+00:00

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.

 Algorithm

  1. open the file in append access mode.
  2. Get the data value for to be inserted in file, from user.
  3. Write the data in the file
  4. Repeat set 2 & 3 if there is more data to be inserted (appended)
  5. 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.

Algorithm

  1. Get the data value to to be inserted with its position.
  2. Open the original file in reading mode.
  3. Open another (temporary) file for writing in it.
  4. Start reading original file sequentially, simultaneously writing it in the temporary file.
  5. This is to be repeated till you reach the position of insertion of new data value.
  6. Write the new value in temporary file.
  7. Repeat step 4 for remaining data of original file.
  8. Delete original file
  9. 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.

 

 

PiRuby is the perfect Tool to Discover Educational Content from Textbooks. Learning and Excellence Made Easy… Really Easy!