Skip to content

Instantly share code, notes, and snippets.

@ytyubox
Last active July 4, 2021 06:33
Show Gist options
  • Save ytyubox/bfcb13a3dd505ae2bfb1c6a642b376cd to your computer and use it in GitHub Desktop.
Save ytyubox/bfcb13a3dd505ae2bfb1c6a642b376cd to your computer and use it in GitHub Desktop.
// getch() equivalent in Swift: read a single character from stdin without a newline
// https://stackoverflow.com/a/59795707
extension FileHandle {
func enableRawMode() -> termios {
var raw = termios()
tcgetattr(self.fileDescriptor, &raw)
let original = raw
raw.c_lflag &= ~UInt(ECHO | ICANON)
tcsetattr(self.fileDescriptor, TCSADRAIN, &raw)
return original
}
func restoreRawMode(originalTerm: termios) {
var term = originalTerm
tcsetattr(self.fileDescriptor, TCSADRAIN, &term)
}
}
func getch() -> UInt8 {
let handle = FileHandle.standardInput
let term = handle.enableRawMode()
defer { handle.restoreRawMode(originalTerm: term) }
var byte: UInt8 = 0
read(handle.fileDescriptor, &byte, 1)
return byte
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment