Is there a way to write a string to a file descriptor without first opening a file there, for e.g. if the shell has set up the file descriptors for you? An equivalent to GNU libc dprintf
, essentially.
Here are two options:
1. Using Foundation
import Foundation
let fd: Int32 = 1 // stdout
let message = "Hello world!\n"
let fileHandle = FileHandle(fileDescriptor: fd)
try fileHandle.write(contentsOf: Data(message.utf8))
2. Using Swift System
This requires adding the swift-system library as a dependency to your package.
import SystemPackage
let fd: Int32 = 1 // stdout
let message = "Hello world!\n"
let desc = FileDescriptor(rawValue: fd)
try desc.writeAll(message.utf8)
4 Likes
Aren’t file descriptors unsigned?
No. They trace back to C, where a negative return value indicates some error condition.
For things like this, which are declared as int
in C, I tend to use Swift’s CInt
.
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple
2 Likes