Skip to content

Instantly share code, notes, and snippets.

@lokshunhung
Last active July 11, 2023 09:54
Show Gist options
  • Select an option

  • Save lokshunhung/2b9d133e7aa7fbaec5bc8ed4892c8d34 to your computer and use it in GitHub Desktop.

Select an option

Save lokshunhung/2b9d133e7aa7fbaec5bc8ed4892c8d34 to your computer and use it in GitHub Desktop.
Swift FileManager usage
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