logo

utils

~/.local/bin tools and git-hooks git clone https://hacktivis.me/git/utils.git
commit: f28d94bc45c365bcece0f7e44e47f6f9f4fa9f13
parent bd586e9fb615da538476cd6e8aa11bfb0380a9c4
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Sun, 30 Jan 2022 15:23:39 +0100

bin/strings: Add support for `-t format` option

Diffstat:

Mbin/strings.c30+++++++++++++++++++++++++-----
1 file changed, 25 insertions(+), 5 deletions(-)

diff --git a/bin/strings.c b/bin/strings.c @@ -15,6 +15,25 @@ size_t opt_min_strlen = 4; char *opt_offset_format = NULL; int +print_string(char *buffer, int offset) +{ + int ret = 0; + + if(opt_offset_format == NULL) { + ret = printf("%s\n", buffer); + } else { + ret = printf(opt_offset_format, offset, buffer); + } + + if(ret < 0) { + fprintf(stderr, "\nError writing: %s\n", strerror(errno)); + return 1; + } else { + return 0; + } +} + +int concat(int fd, const char *fdname) { ssize_t c; @@ -27,10 +46,10 @@ concat(int fd, const char *fdname) while((c = read(fd, read_buf, sizeof(read_buf))) > 0) { - int read_pos; + int read_pos = 0; char b = 0; - for(read_pos = 0; read_pos < c; offset++, read_pos++) + for(;read_pos < c; read_pos++) { b = read_buf[read_pos]; @@ -42,15 +61,16 @@ concat(int fd, const char *fdname) { if(write_pos >= opt_min_strlen) { - write_buf[write_pos++] = '\n'; + write_buf[write_pos + 1] = 0; - if(write(1, write_buf, write_pos) < 0) + if(print_string(write_buf, offset) != 0) { - fprintf(stderr, "\nError writing: %s\n", strerror(errno)); return 1; } } + offset += write_pos; + offset++; write_pos = 0; memset(write_buf, 0, sizeof(write_buf)); }