head.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2018 K. Lange
  5. *
  6. * head - Print the first `n` lines of a file.
  7. */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <unistd.h>
  12. #include <getopt.h>
  13. #include <errno.h>
  14. int main(int argc, char * argv[]) {
  15. int n = 10;
  16. int opt;
  17. int print_names = 0;
  18. int retval = 0;
  19. while ((opt = getopt(argc, argv, "n:")) != -1) {
  20. switch (opt) {
  21. case 'n':
  22. n = atoi(optarg);
  23. break;
  24. }
  25. }
  26. if (argc > optind + 1) {
  27. /* Multiple files */
  28. print_names = 1;
  29. }
  30. if (argc == optind) {
  31. /* This is silly, but should work due to reasons. */
  32. argv[optind] = "-";
  33. argc++;
  34. }
  35. for (int i = optind; i < argc; ++i) {
  36. FILE * f = (!strcmp(argv[i],"-")) ? stdin : fopen(argv[i],"r");
  37. if (!f) {
  38. fprintf(stderr, "%s: %s: %s\n", argv[0], argv[i], strerror(errno));
  39. retval = 1;
  40. continue;
  41. }
  42. if (print_names) {
  43. fprintf(stdout, "==> %s <==\n", (f == stdin) ? "standard input" : argv[i]);
  44. }
  45. int line = 1;
  46. while (!feof(f)) {
  47. int c = fgetc(f);
  48. if (c >= 0) {
  49. fputc(c, stdout);
  50. if (c == '\n') {
  51. line++;
  52. if (line > n) break;
  53. }
  54. }
  55. }
  56. if (f != stdin) {
  57. fclose(f);
  58. }
  59. }
  60. return retval;
  61. }