From d145c5685e84f17fa8ebd935c09bee70b40f6384 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Tue, 13 Feb 2024 22:00:17 +0300 Subject: [PATCH] FileHandlerOutputStream: always check for the file existence --- Sources/FileLogging/swift_log_file.swift | 25 ++++++++++++------------ 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/Sources/FileLogging/swift_log_file.swift b/Sources/FileLogging/swift_log_file.swift index 13a305f..1332226 100644 --- a/Sources/FileLogging/swift_log_file.swift +++ b/Sources/FileLogging/swift_log_file.swift @@ -7,25 +7,24 @@ struct FileHandlerOutputStream: TextOutputStream { case couldNotCreateFile } - private let fileHandle: FileHandle + private let url: URL let encoding: String.Encoding - - init(localFile url: URL, encoding: String.Encoding = .utf8) throws { - if !FileManager.default.fileExists(atPath: url.path) { - guard FileManager.default.createFile(atPath: url.path, contents: nil, attributes: nil) else { - throw FileHandlerOutputStream.couldNotCreateFile - } - } - - let fileHandle = try FileHandle(forWritingTo: url) - fileHandle.seekToEndOfFile() - self.fileHandle = fileHandle + + init(localFile url: URL, encoding: String.Encoding = .utf8) { + self.url = url self.encoding = encoding } mutating func write(_ string: String) { if let data = string.data(using: encoding) { - fileHandle.write(data) + if !FileManager.default.fileExists(atPath: url.path) { + FileManager.default.createFile(atPath: url.path, contents: nil, attributes: nil) + } + + if let fileHandle = try? FileHandle(forWritingTo: url) { + fileHandle.seekToEndOfFile() + fileHandle.write(data) + } } } }