/* reset Faster smaller replacement for ncurses "reset" command. Taylor Gurney, 2022. Public domain. */ #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include #include #include char* argv0; void emsg(const char* s, ...) { va_list ap; int e = errno; fprintf(stderr, "%s: ", argv0); va_start(ap, s); vfprintf(stderr, s, ap); va_end(ap); if (e) { fprintf(stderr, ": %s", strerror(e)); } fputc('\n', stderr); fflush(stderr); } // ANSI codes: // c: reset // (B: set default charset // [0m: reset display attributes // [2J: clear screen const char* RESET_CODE = "\033c\033(B\033[0m\033[2J"; void usage(void) { fprintf(stderr, "usage: %s\n", argv0); exit(1); } ssize_t writeall(int fd, const void* buf, size_t n) { const char* bufptr = (const char*)buf; ssize_t bytes_out = 0; while (n) { bytes_out = write(fd, bufptr, n); if (bytes_out < 0) { return bytes_out; } n -= bytes_out; bufptr += bytes_out; } return bytes_out; } int main(int argc, char* argv[]) { int rval = 0; int fd = 1; int i; struct termios term; argv0 = argv[0]; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--") != 0) { usage(); } } if (!isatty(fd)) { fd = open("/dev/tty", O_RDWR); if (fd < 0) { emsg("%s", "error opening /dev/tty"); exit(1); } } // set sane attributes if (tcgetattr(fd, &term) < 0) { // Move on and still try the ANSI part if this fails. emsg("%s", "tcgetattr failed"); rval = 1; } else { term.c_iflag |= (BRKINT | IGNPAR | ICRNL | IXON); term.c_cflag |= (CREAD | CS8); term.c_lflag |= (ECHO | ECHOE | ECHOK | ICANON | ISIG | IEXTEN); term.c_oflag |= (ONLCR | OPOST); term.c_iflag &= ~(IGNBRK | PARMRK | INPCK | ISTRIP); term.c_iflag &= ~(IGNCR | INLCR | IXANY | IXOFF); term.c_cflag &= ~(CS5 | CS6 | CS7 | CSTOPB | PARENB | PARODD); term.c_lflag &= ~(ECHONL | NOFLSH | TOSTOP); term.c_oflag &= ~(OCRNL | OFILL | ONLRET | ONOCR); if (tcsetattr(fd, TCSADRAIN, &term) < 0) { // NOTE: tcsetattr only returns nonzero if none of the flags // could be applied. So it could partially work and return zero. // Don't care for practical purposes. emsg("%s", "tcsetattr failed"); rval = 1; } } if (writeall(fd, RESET_CODE, strlen(RESET_CODE)) < 0) { if (fd == 1) { emsg("%s", ""); } else { emsg("%s", "/dev/tty"); } rval = 1; } close(fd); return rval; }