Is there a way to receive “unbuffered” input?, like receiving a character once is typed, without having to wait until the EOF or ‘\n’ character to be returned, sorry if it’s a stupid question, since I have recently been able to receive entry for lack of internet guides.
This might be of help to you.
Thank you very much!
The only thing, I had to add a function to come back to normal, because I broke my terminal. ![]()
const std = @import("std");
fn prepare_terminal_for_getch() !void {
// read current settings
var term = try std.posix.tcgetattr(0);
// get chars right away
term.lflag.ICANON = false;
// don't print them
term.lflag.ECHO = false;
// save settings?
try std.posix.tcsetattr(0, std.posix.TCSA.NOW, term);
}
fn repare_terminal() !void {
var term = try std.posix.tcgetattr(0);
term.lflag.ICANON = true;
term.lflag.ECHO = true;
try std.posix.tcsetattr(0, std.posix.TCSA.NOW, term);
}
pub fn main(init: std.process.Init) !void {
try prepare_terminal_for_getch();
var buf: [1024]u8 = undefined;
var stdin_reader = std.Io.File.stdin().reader(init.io, &buf);
const stdin = &stdin_reader.interface;
const input = try stdin.takeByte();
std.log.debug("input: {any}", .{input});
try repare_terminal();
}
reset is typically available as a command on terminal emulators, should your program happen to crash before repairing the terminal.
Hi, you can also defer the repare right after the prepare (ignoring repares failiure, because what would you even do it if failed? is there a recover from that?), to have a bit more robust restoraton. Its really common Zig pattern.
You could also overwrite system interrupt handler / panic handler to have even more robust restoration. (but tbh. i dont think that is necessary)
in a general application setting, it definitely is nice to have, certainly in development: your defer doesn’t run if your code panics or segfaults, even if that panic happens entirely in Zig code, so you’d be left in the “uncooked” terminal state.
the way that libvaxis approaches this is probably worth a peek at!