Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems when writing to file with FileHandler

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?

like image 734
MegaManX Avatar asked Dec 04 '25 14:12

MegaManX


2 Answers

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)
like image 93
Sulthan Avatar answered Dec 06 '25 05:12

Sulthan


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)
like image 45
Werner Altewischer Avatar answered Dec 06 '25 06:12

Werner Altewischer



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!