How can I create an empty file in Swift code, preferably avoiding the Terminal, in as few lines of code as possible? I am using Swift 4, Xcode 9.4.1 and macOS High Sierra. I have tried using the Terminal to run Bash code, see my post here.
Edit:
The question this ones' been marked as duplicate for is for the terminal, which I am trying to avoid now, read that question (which I wrote) to see why.
Edit 2:
If the file already exists, I wish for the code to raise an error to the user, and the code will display it with NSTextField or UILabel.
Thanks in advance! 😅😅
Using your script in the linked question, try:
shell("touch file.txt")
The command touch
will create the file file.txt
.
You do not need the terminal for anything here, just run your .swift
file and you will have your file.
In case you need the file to write to, just use something like this:
let url = URL(fileURLWithPath: "file.txt")
try "Some string".write(to: url, atomically: true, encoding: .utf8)
You file file.txt
will contain the string "Some string" in it.
Update
AFAIK it is not possible to just create a file, but you could create a file with an empty string:
try "".write(to: url, atomically: true, encoding: .utf8)
As mentioned by OP in comment, it is also necessary to disable sandboxing: Remove Sandboxing
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With