print_numbered_lines.c 735 B

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