简体   繁体   中英

Set NSFileHandle seekToFileOffset to end of line

What I want to be able to do is write a string to the end of every line in a file. Right now i have a NSFileHandle writing to the file but only at the end of the file. How can I set it to the end on the line?

You will need to read the stream and search for whatever line delimiter is being used in your file, usually 0x0a (nl), 0x0d (cr), or sometimes cr/lf.

If the file is small enough to read into memory, you could read it into an NSString, use componentsSeparatedByString: (with your delimiter), and then use componentsJoinedByString: (with your end of line addition and the delimiter) to create the aggregate result.

Even if you seek to the end of a line, if you write to the file at the point, you will overwrite the start of the next line. You can't insert text into a file by seeking to a spot and writing.

Your best option is to write out to a temporary file. Open the original file for reading. Read each line and write it to the new file. Then write the text you want to add to the end of the line. Repeat this for each line.

Once you have written all of the new lines to the new file, delete the old file and rename the new file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM