Skip to content

FileHandlerOutputStream: always check for the file existence #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 12 additions & 13 deletions Sources/FileLogging/swift_log_file.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
}
Expand Down