Added a todo file
[iomenu.git] / util.c
blob3a4043604b2a4ac9ca72e02138efa66a96d7cc9b
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <termios.h>
5 #include <unistd.h>
7 #include "util.h"
11 * Reset the terminal state and exit with error.
13 void
14 die(const char *s)
16 /* tcsetattr(STDIN_FILENO, TCSANOW, &termio_old); */
17 fprintf(stderr, "%s\n", s);
18 exit(EXIT_FAILURE);
23 * Set terminal to send one char at a time for interactive mode, and return the
24 * last terminal state.
26 struct termios
27 set_terminal(int tty_fd)
29 struct termios termio_old;
30 struct termios termio_new;
32 /* set the terminal to send one key at a time. */
34 /* get the terminal's state */
35 if (tcgetattr(tty_fd, &termio_old) < 0) {
36 die("Can not get terminal attributes with tcgetattr().");
39 /* create a new modified state by switching the binary flags */
40 termio_new = termio_old;
41 termio_new.c_lflag &= ~(ICANON | ECHO | IGNBRK);
43 /* apply this state to current terminal now (TCSANOW) */
44 tcsetattr(tty_fd, TCSANOW, &termio_new);
46 return termio_old;
51 * Replace tab as a multiple of 8 spaces in a line.
53 * Allocates memory.
55 char *
56 expand_tabs(char *line)
58 size_t i, n;
59 char *converted = malloc(sizeof(char) * (strlen(line) * 8 + 1));
61 for (i = 0, n = 0; i < strlen(line); i++, n++) {
62 if (line[i] == '\t') {
63 for (; n == 0 || n % 8 != 0; n++)
64 converted[n] = ' ';
65 n--;
66 } else {
67 converted[n] = line[i];
71 converted[n] = '\0';
73 return converted;