Skip to content

Instantly share code, notes, and snippets.

@preveen-stack
Created May 7, 2023 16:18
Show Gist options
  • Save preveen-stack/bf8a22e917fca9fba0c9a531cd11a568 to your computer and use it in GitHub Desktop.
Save preveen-stack/bf8a22e917fca9fba0c9a531cd11a568 to your computer and use it in GitHub Desktop.
get the size of the terminal in rust
[dependencies]
libc = "0.2"
extern crate libc;

use std::mem;
use std::os::unix::io::AsRawFd;

fn main() {
    let fd = std::io::stdout().as_raw_fd();
    let mut winsize: libc::winsize = unsafe { mem::zeroed() };

    if unsafe { libc::ioctl(fd, libc::TIOCGWINSZ, &mut winsize) } == -1 {
        panic!("Failed to get window size: {:?}", std::io::Error::last_os_error());
    }

    let rows = winsize.ws_row as usize;
    let cols = winsize.ws_col as usize;

    println!("Window size is {}x{}", cols, rows);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment