head.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* head - print file until a certain line
  2. * Copyright (C) 2022 Ferass EL HAFIDI
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. void printUsage() {
  21. printf("Ferass' Base System.\n\n"
  22. "Usage: head [FILE] [-n NUMBER]\n\n"
  23. "Print FILE's contents until line NUMBER.\n\n"
  24. "\t-n NUMBER\tPrint first NUMBER line(s).\n"
  25. );
  26. }
  27. int main(int argc, char *argv[]) {
  28. FILE *file;
  29. char s[512], arg_lines;
  30. int i = 0, usedargs = 0;
  31. setvbuf(stdout, NULL, _IONBF, 0);
  32. if (argc == 1) {
  33. while (1) {
  34. char input[80];
  35. fgets(input, 80, stdin);
  36. printf("%s", input);
  37. }
  38. }
  39. for (i = 1; argv[i]; i++) {
  40. if (argv[i][usedargs + 1] == 'n' && argv[i + 1]) {
  41. arg_lines = strtol(argv[i + 1], NULL, 0);
  42. usedargs++;
  43. }
  44. if (argv[i][usedargs + 1] == 'h') {
  45. printUsage();
  46. return 0;
  47. }
  48. }
  49. if ((file = fopen(argv[1], "r")) == NULL) {
  50. printf("head: %s: No such file or directory\n", argv[1]);
  51. return 1;
  52. }
  53. for (; i != arg_lines && (fgets(s, 512, file)) != NULL; i++) {
  54. s[strcspn(s, "\n")] = 0; /* Remove trailing newline */
  55. puts(s);
  56. }
  57. fclose(file);
  58. return 0;
  59. }