print_numbered_lines.c 672 B

123456789101112131415161718192021222324252627282930
  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. #include "libbb.h"
  9. void FAST_FUNC print_numbered_lines(struct number_state *ns, const char *filename)
  10. {
  11. FILE *fp = fopen_or_warn_stdin(filename);
  12. unsigned N = ns->start;
  13. char *line;
  14. while ((line = xmalloc_fgetline(fp)) != NULL) {
  15. if (ns->all
  16. || (ns->nonempty && line[0])
  17. ) {
  18. printf("%*u%s%s\n", ns->width, N, ns->sep, line);
  19. N += ns->inc;
  20. } else if (ns->empty_str)
  21. fputs(ns->empty_str, stdout);
  22. free(line);
  23. }
  24. ns->start = N;
  25. fclose(fp);
  26. }