]> git.lizzy.rs Git - center.git/blobdiff - center.c
Add new target clean
[center.git] / center.c
index e8097d2fe4463ddfb2c5f86f2ac782ba0e13d83c..a08e9e7349ce1082fdd784ae7ae3e21a9fc6723f 100644 (file)
--- a/center.c
+++ b/center.c
@@ -1,12 +1,15 @@
 #define _POSIX_C_SOURCE 200809L
 #define _XOPEN_SOURCE
+#include <fcntl.h>
+#include <locale.h>
 #include <stdio.h>
-#include <wchar.h>
 #include <stdlib.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/types.h>
 #include <termios.h>
 #include <unistd.h>
-#include <sys/ioctl.h>
-#include <locale.h>
+#include <wchar.h>
 
 #define ERR(str) { perror(str); err = EXIT_FAILURE; goto end; }
 
@@ -22,9 +25,15 @@ int main()
        ssize_t len;
        int err = EXIT_SUCCESS;
 
+       int tty_fd = open("/dev/tty", O_RDWR);
+       if (tty_fd < 0) {
+               perror("open");
+               return EXIT_FAILURE;
+       }
+
        while ((len = getline(&buf, &siz, stdin)) > 0) {
                struct winsize ws;
-               if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0) ERR("ioctl")
+               if (ioctl(tty_fd, TIOCGWINSZ, &ws) < 0) ERR("ioctl")
 
                int term_width = ws.ws_col;
 
@@ -39,9 +48,6 @@ int main()
                        size_t adv = mbrtowc(&wc, ptr, len, &mbs);
                        if (adv == (size_t) -1 || adv == (size_t) -2) ERR("mbrtowc")
 
-                       ptr += adv;
-                       len -= adv;
-
                        int width = wcwidth(wc);
                        if (width > 0)
                                str_width += width;
@@ -54,13 +60,18 @@ int main()
                                if (*ptr != '\n')
                                        putchar('\n');
 
-                               last = ptr + 1;
+                               last = ptr + adv;
                                str_width = 0;
                        }
+
+                       ptr += adv;
+                       len -= adv;
                }
        }
 
        end:
+       close(tty_fd);
+
        if (buf)
                free(buf);