I have a code that looks like this:
let fileName = "name.txt"
let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
try! "".write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
let fileHandle = try! FileHandle(forWritingTo: fileURL)
fileHandle.seekToEndOfFile()
And this code works. But if i remove the line:
try! "".write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
I get runtime exception. I am not sure why this line is needed?
If you look into the docs for FileHandle(forWritingTo:), the return value is specified as:
The initialized file handle object or nil if no file exists at url.
The file has to exist, otherwise nil is returned.
The
try! "".write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
creates the file.
If you don't create the file and the file does not exist, trying to open the file using FileHandle will crash the app.
The code would be probably more readable, if you created the file explicitly:
FileManager.default.createFile(atPath: fileURL.path, contents: nil)
A better implementation is to use a POSIX file descriptor which allows you to create the file if it does not exist or truncate it to zero length if it does, all in one operation (it also allows more flags, e.g. for exclusive locking):
let fileDescriptor = open(fileURL.path, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR)
if fileDescriptor == -1 {
let posixErrorCode = POSIXErrorCode(rawValue: errno)!
throw POSIXError(posixErrorCode)
}
let fileHandle = FileHandle(fileDescriptor: fileDescriptor, closeOnDealloc: true)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With