Question

I have a very large text file, and my iPad program needs to occasionally replace a single line of data (newline: '\n'). How can I do this efficiently? Writing the entire file at once is not an option.

I've been looking into NSFileHandle, and it looks like it will do what I want; right now I'm having trouble figuring out how to find line X, and then replace it with the data from a string. I think after that's done, all I need to do is call synchronizeFile, right?

I appreciate your help!

Was it helpful?

Solution

You cannot really do this without writing the whole file. You could seek to the beginning of the line and then write the new line. But first you’d have to find out the offset of that line. If you don’t already have that this means reading the file from the beginning to that line. Then you could write the new line, but only if it is exactly the same length as the original line. If it is longer it will overwrite the next line - there is no way to insert data into a file. If the new line is shorter than the old one the end of the old line will remain. The same length requirement is also tricky. This means the same length in bytes. Depending on the character encoding some characters might require more bytes than others.

If you really need to do this and have it work for about every case you’d have to use those steps:

  1. Read the entire file to find out the offset of the line you’re interested in
  2. Seek to the offset of the line
  3. Write the new line
  4. Write out the rest of the file you read in step 1.

This algorithm will work, no matter how long or short the lines are or how they are encoded. But this will probably be more expensive than just writing out the whole file, especially if you have it in memory anyways.

Have you actually verified that it is not acceptable to write out the whole file or are you doing premature optimization here? If your text file is really that big you should be considering a database, like SQLite, or to use Core Data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top