ttysize.c 982 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Replacement for "stty size", which is awkward for shell script use.
  4. * - Allows to request width, height, or both, in any order.
  5. * - Does not complain on error, but returns width 80, height 24.
  6. * - Size: less than 200 bytes
  7. *
  8. * Copyright (C) 2007 by Denys Vlasenko <vda.linux@googlemail.com>
  9. *
  10. * Licensed under GPLv2, see file LICENSE in this source tree.
  11. */
  12. #include "libbb.h"
  13. int ttysize_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  14. int ttysize_main(int argc UNUSED_PARAM, char **argv)
  15. {
  16. unsigned w, h;
  17. struct winsize wsz;
  18. w = 80;
  19. h = 24;
  20. if (!ioctl(0, TIOCGWINSZ, &wsz)) {
  21. w = wsz.ws_col;
  22. h = wsz.ws_row;
  23. }
  24. if (!argv[1]) {
  25. printf("%u %u", w, h);
  26. } else {
  27. const char *fmt, *arg;
  28. fmt = "%u %u" + 3; /* "%u" */
  29. while ((arg = *++argv) != NULL) {
  30. char c = arg[0];
  31. if (c == 'w')
  32. printf(fmt, w);
  33. if (c == 'h')
  34. printf(fmt, h);
  35. fmt = "%u %u" + 2; /* " %u" */
  36. }
  37. }
  38. bb_putchar('\n');
  39. return 0;
  40. }