Denys Vlasenko | d9eb40c | 2017-04-12 15:48:19 +0200 | [diff] [blame] | 1 | /* vi: set sw=4 ts=4: */ |
| 2 | /* |
| 3 | * Copyright (C) 2017 Denys Vlasenko <vda.linux@googlemail.com> |
| 4 | * |
| 5 | * Licensed under GPLv2, see file LICENSE in this source tree. |
| 6 | */ |
| 7 | //kbuild:lib-y += print_numbered_lines.o |
| 8 | |
| 9 | #include "libbb.h" |
| 10 | |
Denys Vlasenko | c100535 | 2018-11-29 11:44:10 +0100 | [diff] [blame] | 11 | int FAST_FUNC print_numbered_lines(struct number_state *ns, const char *filename) |
Denys Vlasenko | d9eb40c | 2017-04-12 15:48:19 +0200 | [diff] [blame] | 12 | { |
| 13 | FILE *fp = fopen_or_warn_stdin(filename); |
Denys Vlasenko | c100535 | 2018-11-29 11:44:10 +0100 | [diff] [blame] | 14 | unsigned N; |
Denys Vlasenko | d9eb40c | 2017-04-12 15:48:19 +0200 | [diff] [blame] | 15 | char *line; |
| 16 | |
Denys Vlasenko | c100535 | 2018-11-29 11:44:10 +0100 | [diff] [blame] | 17 | if (!fp) |
| 18 | return EXIT_FAILURE; |
| 19 | |
| 20 | N = ns->start; |
Denys Vlasenko | d9eb40c | 2017-04-12 15:48:19 +0200 | [diff] [blame] | 21 | while ((line = xmalloc_fgetline(fp)) != NULL) { |
| 22 | if (ns->all |
| 23 | || (ns->nonempty && line[0]) |
| 24 | ) { |
Ron Yorston | c849e72 | 2021-01-21 08:40:54 +0000 | [diff] [blame] | 25 | printf("%*u%s", ns->width, N, ns->sep); |
Denys Vlasenko | d9eb40c | 2017-04-12 15:48:19 +0200 | [diff] [blame] | 26 | N += ns->inc; |
| 27 | } else if (ns->empty_str) |
Ron Yorston | cad3fc7 | 2021-02-03 20:47:14 +0100 | [diff] [blame] | 28 | fputs_stdout(ns->empty_str); |
Ron Yorston | c849e72 | 2021-01-21 08:40:54 +0000 | [diff] [blame] | 29 | puts(line); |
Denys Vlasenko | d9eb40c | 2017-04-12 15:48:19 +0200 | [diff] [blame] | 30 | free(line); |
| 31 | } |
Denys Vlasenko | 75e90b1 | 2017-07-14 10:47:18 +0200 | [diff] [blame] | 32 | ns->start = N; |
Denys Vlasenko | d9eb40c | 2017-04-12 15:48:19 +0200 | [diff] [blame] | 33 | |
| 34 | fclose(fp); |
Denys Vlasenko | c100535 | 2018-11-29 11:44:10 +0100 | [diff] [blame] | 35 | |
| 36 | return EXIT_SUCCESS; |
Denys Vlasenko | d9eb40c | 2017-04-12 15:48:19 +0200 | [diff] [blame] | 37 | } |