Last active
July 11, 2023 09:54
-
-
Save lokshunhung/2b9d133e7aa7fbaec5bc8ed4892c8d34 to your computer and use it in GitHub Desktop.
Swift FileManager usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| @main struct FileScratch { | |
| static func main() { | |
| let fm: FileManager = .default | |
| let home: URL = fm.homeDirectoryForCurrentUser | |
| // Older API for `.appending(path:directoryHint:)`: `.appendingPathComponent(_:)` | |
| // https://developer.apple.com/documentation/foundation/url/1780239-appendingpathcomponent | |
| let outputFile = home | |
| .appending(path: "Desktop") | |
| .appending(path: "tmp") | |
| .appending(path: "output.txt") | |
| let outputDir = outputFile.deletingLastPathComponent() | |
| if !fm.directoryExists(at: outputDir.path(percentEncoded: false)) { | |
| try? fm.createDirectory(at: outputDir, withIntermediateDirectories: true) | |
| } | |
| if !fm.fileExists(atPath: outputFile.path(percentEncoded: false)) { | |
| fm.createFile(atPath: outputFile.path(percentEncoded: false), contents: nil) | |
| } | |
| guard let outputFileHandle = try? FileHandle(forUpdating: outputFile) else { | |
| print("cannot open file at \(outputFile.path(percentEncoded: false))") | |
| return | |
| } | |
| defer { try? outputFileHandle.close() } | |
| // try? outputFileHandle.truncate(atOffset: 0) // <-- clear all | |
| _ = try? outputFileHandle.seekToEnd() // <-- move cursor to end | |
| try? outputFileHandle.write(contentsOf: "text".data(using: .utf8)!) | |
| try? outputFileHandle.write(contentsOf: "\n".data(using: .utf8)!) | |
| try? outputFileHandle.synchronize() // <-- flush | |
| try? outputFileHandle.write(contentsOf: "end".data(using: .utf8)!) | |
| } | |
| } | |
| private extension FileManager { | |
| func directoryExists(at path: String) -> Bool { | |
| var isDirectory: ObjCBool = false | |
| let exists = self.fileExists(atPath: path, isDirectory: &isDirectory) | |
| return exists && isDirectory.boolValue | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment