Home > Software engineering >  How do i start reading a text file from a specific point?
How do i start reading a text file from a specific point?

Time:11-30

So my question is basically, how do i start reading a file from a specific line, like for example line 14 until line 18?

Im working on a simple ContactList app and the only thing missing is deleting the information from a specific name. The user can create a new contact which has a name, a number and an address as information. I want the user to also be able to delete the data of that person by typing in their name. Then, the program should read the name and all of the 4 lines under it and remove them from the text File. How could i achieve this?

CodePudding user response:

You can jump to any offset within a file. However, there isn't any way to know where a particular line begins unless you know the length of every line.

If you are writing a contact app, you should not use a regular text file unless:

  1. You pad line lengths so that you can easily calculate the position of each line.
  2. You are loading the entire file into memory.

CodePudding user response:

You can't. You need to read the first n lines in order to find out which line has which number. Except if your records have a fixed length per line (which is not a good idea - there's always someone with a longer name that you could think of).

Likewise, you can't delete a line from the text file. The space on disk does not move by itself. You need an algorithm that implements safe saving and rearranges the data:

foreach line in input_file:
    if line is needed:
        write line to temporary_output_file
    else:
        ignore (don't write = delete)
delete input_file
move temporary_output_file to input_file

Disadvantage: you need about double the disk space while input_file and temporary_output_file both exist.

With safe saving, the NTFS file system driver will give the moved file the same time stamp that it had before deleting the file. Read the Windows Internals 7 book (should be part 2, chapter 11) to understand it in detail.

Depending on how large the contact list is (probably it's less than 10M entries), there's no problem of loading the whole database into memory, deleting the record and then writing everything back.

  • Related