Frage

Ich habe eine sehr große Textdatei, und mein iPad Programm geht gelegentlich eine einzige Zeile von Daten ersetzen (Newline: ‚\ n‘). Wie kann ich dies effizient tun? Schreibt die gesamte Datei auf einmal ist keine Option.

Ich habe mich in NSFileHandle, und es sieht aus wie es tun, was ich will; jetzt Mühe, herauszufinden, ich habe wie Linie X zu finden, und ersetzen Sie es dann mit den Daten aus einem String. Ich denke, nach dem erledigt ist, alles, was ich tun muß, ist Anruf synchronizeFile, nicht wahr?

Ich schätze Ihre Hilfe!

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top