cat.c 896 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. void cat_file(const char *file_path)
  6. {
  7. FILE *f = fopen(file_path, "r");
  8. if (f == NULL) {
  9. fprintf(stderr, "ERROR: could not open file %s: %s\n",
  10. file_path, strerror(errno));
  11. exit(1);
  12. }
  13. static char cat_buffer[4098];
  14. while (!feof(f)) {
  15. size_t n = fread(cat_buffer,
  16. sizeof(cat_buffer[0]),
  17. sizeof(cat_buffer) / sizeof(cat_buffer[0]),
  18. f);
  19. fwrite(cat_buffer,
  20. sizeof(cat_buffer[0]),
  21. n,
  22. stdout);
  23. }
  24. fclose(f);
  25. }
  26. int main(int argc, char **argv)
  27. {
  28. if (argc < 2) {
  29. fprintf(stderr, "USAGE: cat <files...>");
  30. exit(1);
  31. }
  32. for (int i = 1; i < argc; ++i) {
  33. cat_file(argv[i]);
  34. }
  35. return 0;
  36. }