FileHandle(forWritingTo: writes to the top of a file. Can this be fixed?

Swift app is launching an instance of itself. When it does that it sets the output using FileHandle(forWritingTo: & ends up writing to the top of the target file, not appending to the end.


The output is landing in the right file, but at the top. Any idea why & how this can be fixed ?


do{

let opURL = URL(string: "file:///Users/j238/output.txt")

let opFile = try FileHandle(forWritingTo: self.opURL!)

task.standardOutput = opFile

task.standardError = opFile

}catch let error as NSError {

print("Ooops! Something went wrong with setting output: \(error)")

}

Replies

You can do one of two things:

1) Open the file for updating, seek to the end, and start writing there

2) Open a low-level file descriptor for appending. Then create a FileHandle from that descriptor.

Assuming other parts of your code is working correctly, call `seekToEndOfFile()` after you instantiate the FileHandle.

            let opFile = try FileHandle(forWritingTo: opURL)
            opFile.seekToEndOfFile()

One thing to watch out for here is concurrency. If multiple threads are writing to the same file, OOPer’s nice solution, based on

seekToEndOfFile
, isn’t reliable. Instead, you need to open the file with the
O_APPEND
flag.
FileHandle
doesn’t expose that, so you’ll need to use the low-level
open
call and wrap that in a file handle per john daniel’s second option.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"