cat.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* cat - concatenate a file to stdout
  2. * Copyright (C) 2022 Ferass EL HAFIDI
  3. * Copyright (C) 2022 Leah Rowe
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. #include <fcntl.h>
  19. #include <unistd.h>
  20. #include <stdio.h>
  21. int getopt(int argc, char *const argv[], const char *optstring);
  22. void printUsage() {
  23. printf("Ferass' Base System.\n\n"
  24. "Usage: cat [FILE]\n\n"
  25. "Concatenate FILE to stdout\n\n");
  26. }
  27. int main(int argc, char *const argv[]) {
  28. int file, argument;
  29. char s[4096], input[4096];
  30. setvbuf(stdout, NULL, _IONBF, 0);
  31. if (argc == 1) {
  32. while (1) {
  33. read(STDIN_FILENO, input, 4096);
  34. printf("%s", input);
  35. }
  36. }
  37. while ((argument = getopt(argc, argv, "h")) != -1) {
  38. if (argument == 'h') {
  39. printUsage();
  40. return 0;
  41. } else return 1;
  42. }
  43. if ((file=open(argv[1], O_RDONLY)) == -1) {
  44. printf("cat: %s: No such file or directory\n", argv[1]);
  45. return 1;
  46. }
  47. while (read(file, s, 4096) > 0)
  48. printf("%s", s);
  49. close(file);
  50. return 0;
  51. }