cat.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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) 2013-2018 K. Lange
  5. *
  6. * cat - Concatenate files
  7. *
  8. * Concatenates files together to standard output.
  9. * In a supporting terminal, you can then pipe
  10. * standard out to another file or other useful
  11. * things like that.
  12. */
  13. #include <stdio.h>
  14. #include <fcntl.h>
  15. #include <unistd.h>
  16. #include <string.h>
  17. #include <errno.h>
  18. #include <sys/stat.h>
  19. #define CHUNK_SIZE 4096
  20. void doit(int fd) {
  21. while (1) {
  22. char buf[CHUNK_SIZE];
  23. memset(buf, 0, CHUNK_SIZE);
  24. ssize_t r = read(fd, buf, CHUNK_SIZE);
  25. if (!r) return;
  26. write(STDOUT_FILENO, buf, r);
  27. }
  28. }
  29. int main(int argc, char ** argv) {
  30. int ret = 0;
  31. if (argc == 1) {
  32. doit(0);
  33. }
  34. for (int i = 1; i < argc; ++i) {
  35. int fd = open(argv[i], O_RDONLY);
  36. if (fd < 0) {
  37. fprintf(stderr, "%s: %s: %s\n", argv[0], argv[i], strerror(errno));
  38. ret = 1;
  39. continue;
  40. }
  41. struct stat _stat;
  42. fstat(fd, &_stat);
  43. if (S_ISDIR(_stat.st_mode)) {
  44. fprintf(stderr, "%s: %s: Is a directory\n", argv[0], argv[i]);
  45. close(fd);
  46. ret = 1;
  47. continue;
  48. }
  49. doit(fd);
  50. close(fd);
  51. }
  52. return ret;
  53. }