3

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!

7ball
  • 2,183
  • 4
  • 26
  • 61

2 Answers2

5

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
4

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.

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • Yeah, I found a pretty nice way to do it in Linux like so `echo "text to prepend $(cat file.txt)" > file.txt`, but like you said, it's not straightforward to do. – 7ball Feb 15 '17 at 22:44