blob: b64f855973d40406915abf7421c2bbe6d10c952c [file] [log] [blame]
Denys Vlasenkod9eb40c2017-04-12 15:48:19 +02001/* 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 Vlasenkoc1005352018-11-29 11:44:10 +010011int FAST_FUNC print_numbered_lines(struct number_state *ns, const char *filename)
Denys Vlasenkod9eb40c2017-04-12 15:48:19 +020012{
13 FILE *fp = fopen_or_warn_stdin(filename);
Denys Vlasenkoc1005352018-11-29 11:44:10 +010014 unsigned N;
Denys Vlasenkod9eb40c2017-04-12 15:48:19 +020015 char *line;
16
Denys Vlasenkoc1005352018-11-29 11:44:10 +010017 if (!fp)
18 return EXIT_FAILURE;
19
20 N = ns->start;
Denys Vlasenkod9eb40c2017-04-12 15:48:19 +020021 while ((line = xmalloc_fgetline(fp)) != NULL) {
22 if (ns->all
23 || (ns->nonempty && line[0])
24 ) {
Ron Yorstonc849e722021-01-21 08:40:54 +000025 printf("%*u%s", ns->width, N, ns->sep);
Denys Vlasenkod9eb40c2017-04-12 15:48:19 +020026 N += ns->inc;
27 } else if (ns->empty_str)
Ron Yorstoncad3fc72021-02-03 20:47:14 +010028 fputs_stdout(ns->empty_str);
Ron Yorstonc849e722021-01-21 08:40:54 +000029 puts(line);
Denys Vlasenkod9eb40c2017-04-12 15:48:19 +020030 free(line);
31 }
Denys Vlasenko75e90b12017-07-14 10:47:18 +020032 ns->start = N;
Denys Vlasenkod9eb40c2017-04-12 15:48:19 +020033
34 fclose(fp);
Denys Vlasenkoc1005352018-11-29 11:44:10 +010035
36 return EXIT_SUCCESS;
Denys Vlasenkod9eb40c2017-04-12 15:48:19 +020037}