Skip to content

Commit

Permalink
Use ioctl instead of requiring curses (#1)
Browse files Browse the repository at this point in the history
  • Loading branch information
Qix- authored and sindresorhus committed May 7, 2017
1 parent ecb2bc7 commit 6069985
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 23 deletions.
2 changes: 1 addition & 1 deletion build
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#!/usr/bin/env sh

clang -Ofast -Wall -Wextra -Werror -pedantic -lcurses term-size.c -o term-size
clang -Ofast -Wall -Wextra -Werror -pedantic -std=c99 term-size.c -o term-size
34 changes: 12 additions & 22 deletions term-size.c
Original file line number Diff line number Diff line change
@@ -1,37 +1,27 @@
#include <stdio.h>
#include <string.h> // strerror
#include <errno.h> // errno
#include <fcntl.h> // open(), O_RDONLY
#include <unistd.h> // close()
#include <curses.h> // setupterm(), tigetnum()
#include <term.h> // ^ Same as above
#include <string.h> // strerror
#include <errno.h> // errno
#include <fcntl.h> // open(), O_RDONLY
#include <unistd.h> // close()
#include <sys/ioctl.h> // ioctl()

int main() {
int tty_fd = open("/dev/tty", O_RDONLY);
int tty_fd = open("/dev/tty", O_EVTONLY | O_NONBLOCK);
if (tty_fd == -1) {
fprintf(stderr, "Opening `/dev/tty` failed (%d): %s\n", errno, strerror(errno));
return 1;
}

// Intentionally not handling errors as none of
// the documented errors can happen on macOS
setupterm("xterm", tty_fd, NULL);
struct winsize ws;
int result = ioctl(tty_fd, TIOCGWINSZ, &ws);
close(tty_fd);

int cols = tigetnum("cols");
if (cols < 0) {
fprintf(stderr, "tigetnum(\"cols\") returned error code %d\n", cols);
close(tty_fd);
if (result == -1) {
fprintf(stderr, "Getting size failed (%d): %s\n", errno, strerror(errno));
return 1;
}

int rows = tigetnum("lines");
if (rows < 0) {
fprintf(stderr, "tigetnum(\"lines\") returned error code %d\n", rows);
close(tty_fd);
return 1;
}

fprintf(stdout, "%d\n%d\n", cols, rows);
fprintf(stdout, "%d\n%d\n", ws.ws_col, ws.ws_row);
return 0;
}

0 comments on commit 6069985

Please sign in to comment.