head.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /* SPDX-License-Identifier: BSD-3-Clause */
  2. /*
  3. * Copyright (C) 2022, 2023 Ferass El Hafidi <vitali64pmemail@protonmail.com>
  4. * Copyright (C) 2022 Leah Rowe <leah@libreboot.org>
  5. */
  6. #include <fcntl.h>
  7. #include <unistd.h>
  8. #include <stdio.h>
  9. #include <errno.h>
  10. #include <string.h>
  11. #include <stdlib.h>
  12. #define REQ_PRINT_USAGE /* Require print_usage() from ../common/common.h */
  13. #define REQ_ERRPRINT /* Require errprint() from ../common/common.h */
  14. #define DESCRIPTION "Copy file to standard output until <number> lines."
  15. #define OPERANDS "[-n number] [file] ..."
  16. #include "../common/common.h"
  17. int main(int argc, char *const argv[]) {
  18. int argument, i, lines = 10, lines_printed;
  19. FILE *file;
  20. char s[4096], *argv0 = strdup(argv[0]);
  21. while ((argument = getopt(argc, argv, "n:")) != -1) {
  22. if (argument == '?' || argument == ':') {
  23. print_usage(argv[0], DESCRIPTION, OPERANDS, VERSION);
  24. return 1;
  25. }
  26. else if (argument == 'n') {
  27. lines = strtol(optarg, NULL, 10);
  28. if (errno) return errprint(argv[0], "strtol()", errno);
  29. }
  30. else
  31. lines = 10;
  32. } argc -= optind; argv += optind;
  33. for (i = 0; i != argc || argc == 0; i++) {
  34. if (argc == 0 || !strcmp(argv[i], "-"))
  35. file = stdin;
  36. else file = fopen(argv[i], "r");
  37. if (file == NULL)
  38. return errprint(argv0, argv[i], errno); /* Something went wrong */
  39. for (lines_printed = 1; lines_printed <= lines; lines_printed++) {
  40. if (fgets(s, 4096, file) != NULL)
  41. printf("%s", s);
  42. else return errprint(argv0, "fgets()", errno);
  43. }
  44. if (file != stdin) fclose(file);
  45. if (argc == 0) return 0; /* TODO: Remove this stupid hack. */
  46. }
  47. return errprint(argv0, NULL, errno);
  48. }