Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to PREPEND text to a file in Swift or Objective C?

Please note that I'm not asking how to append texts at the end of the file. I'm asking how to prepend texts to the beginning of file.

let handle = try FileHandle(forWritingTo: someFile)
//handle.seekToEndOfFile() // This is for appending
handle.seek(toFileOffset: 0) // Me trying to seek to the beginning of file
handle.write(content)
handle.closeFile()

It seems like my content is being written at the beginning of the file, but it just replaces the existing consent as well... Thanks!

like image 808
7ball Avatar asked Oct 12 '25 09:10

7ball


2 Answers

One reasonable solution is to write the new content to a temporary file, then append the existing contents to the end of the temporary file. Then move the temporary file over the old file.

When you seek to a point in an existing file and then perform a write, the existing contents are overwritten from that point. This is why your current approach fails.

like image 79
rmaddy Avatar answered Oct 14 '25 04:10

rmaddy


In general, most file systems don't have built-in support for prepending data to files. Likewise, most file I/O APIs don't either.

In order to prepend data, you first have to shift all of the existing data further along the file to make room for the new data at the beginning. You typically do this by starting near the end, reading a chunk of data, writing that data to the original position plus the length of data you hope to eventually prepend, and then repeating with the next chunk closer to the beginning of the file. In this way, you gradually shift everything down. Only after you've done all of that can you safely write the new data at the beginning of the file safely.

Frankly, if there's any way to avoid this, you should try to. The performance is likely to be terrible if the file is large and/or you're doing it frequently.

like image 38
Ken Thomases Avatar answered Oct 14 '25 03:10

Ken Thomases



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!