cat.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #define REQ_PRINT_USAGE /* Require print_usage() from ../common/common.h */
  12. #define REQ_ERRPRINT /* Require errprint() from ../common/common.h */
  13. #define DESCRIPTION "Concatenate a file to standard output. \
  14. If no file is specified or file is '-', read standard input."
  15. #define OPERANDS "[-u] [file] ..."
  16. #include "../common/common.h"
  17. int cat(int flides, int unbuffered);
  18. int main(int argc, char *const argv[]) {
  19. int file, argument, i = 1, unbuffered, err;
  20. char *argv0 = strdup(argv[0]);
  21. while ((argument = getopt(argc, argv, "u")) != -1) {
  22. if (argument == '?') {
  23. print_usage(argv[0], DESCRIPTION, OPERANDS, VERSION);
  24. return 1;
  25. }
  26. else if (argument == 'u')
  27. unbuffered = 1;
  28. } argc -= optind; argv += optind;
  29. if (argc < 1) {
  30. return errprint(argv0, "-", cat(STDIN_FILENO, unbuffered));
  31. }
  32. for (i = 0; i != argc; i++) {
  33. if (strcmp(argv[i], "-")) file = open(argv[i], O_RDONLY);
  34. else file = STDIN_FILENO;
  35. if (file == -1)
  36. return errprint(argv0, argv[i], errno); /* Something went wrong */
  37. err = errprint(argv0, argv[i], cat(file, unbuffered));
  38. close(file);
  39. }
  40. return err;
  41. }
  42. int cat(int fildes, int unbuffered) {
  43. char s[4096];
  44. FILE *filstr;
  45. size_t length;
  46. if (unbuffered) while ((length = read(fildes, s, 4096)) > 0)
  47. write(STDOUT_FILENO, s, length);
  48. else {
  49. if (fildes != STDIN_FILENO) filstr = fdopen(fildes, "r");
  50. else filstr = stdin;
  51. while ((length = fread(s, 4096, 1, filstr)) > 0)
  52. fwrite(s, length, 1, stdout);
  53. }
  54. if (errno) return errno;
  55. return 0;
  56. }