ttysize.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. //config:config TTYSIZE
  13. //config: bool "ttysize"
  14. //config: default y
  15. //config: help
  16. //config: A replacement for "stty size". Unlike stty, can report only width,
  17. //config: only height, or both, in any order. It also does not complain on
  18. //config: error, but returns default 80x24.
  19. //config: Usage in shell scripts: width=`ttysize w`.
  20. //applet:IF_TTYSIZE(APPLET(ttysize, BB_DIR_USR_BIN, BB_SUID_DROP))
  21. //kbuild:lib-$(CONFIG_TTYSIZE) += ttysize.o
  22. //usage:#define ttysize_trivial_usage
  23. //usage: "[w] [h]"
  24. //usage:#define ttysize_full_usage "\n\n"
  25. //usage: "Print dimension(s) of stdin's terminal, on error return 80x25"
  26. #include "libbb.h"
  27. int ttysize_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  28. int ttysize_main(int argc UNUSED_PARAM, char **argv)
  29. {
  30. unsigned w, h;
  31. struct winsize wsz;
  32. w = 80;
  33. h = 24;
  34. if (!ioctl(0, TIOCGWINSZ, &wsz)) {
  35. w = wsz.ws_col;
  36. h = wsz.ws_row;
  37. }
  38. if (!argv[1]) {
  39. printf("%u %u", w, h);
  40. } else {
  41. const char *fmt, *arg;
  42. fmt = "%u %u" + 3; /* "%u" */
  43. while ((arg = *++argv) != NULL) {
  44. char c = arg[0];
  45. if (c == 'w')
  46. printf(fmt, w);
  47. if (c == 'h')
  48. printf(fmt, h);
  49. fmt = "%u %u" + 2; /* " %u" */
  50. }
  51. }
  52. bb_putchar('\n');
  53. return 0;
  54. }