busybox/libbb/print_numbered_lines.c
<<
>>
Prefs
   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
  11int FAST_FUNC print_numbered_lines(struct number_state *ns, const char *filename)
  12{
  13        FILE *fp = fopen_or_warn_stdin(filename);
  14        unsigned N;
  15        char *line;
  16
  17        if (!fp)
  18                return EXIT_FAILURE;
  19
  20        N = ns->start;
  21        while ((line = xmalloc_fgetline(fp)) != NULL) {
  22                if (ns->all
  23                 || (ns->nonempty && line[0])
  24                ) {
  25                        printf("%*u%s", ns->width, N, ns->sep);
  26                        N += ns->inc;
  27                } else if (ns->empty_str)
  28                        fputs_stdout(ns->empty_str);
  29                puts(line);
  30                free(line);
  31        }
  32        ns->start = N;
  33
  34        fclose(fp);
  35
  36        return EXIT_SUCCESS;
  37}
  38