splice_read.c 998 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // SPDX-License-Identifier: GPL-2.0
  2. #define _GNU_SOURCE
  3. #include <errno.h>
  4. #include <fcntl.h>
  5. #include <limits.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <unistd.h>
  9. #include <sys/types.h>
  10. #include <sys/stat.h>
  11. int main(int argc, char *argv[])
  12. {
  13. int fd;
  14. size_t size;
  15. ssize_t spliced;
  16. if (argc < 2) {
  17. fprintf(stderr, "Usage: %s INPUT [BYTES]\n", argv[0]);
  18. return EXIT_FAILURE;
  19. }
  20. fd = open(argv[1], O_RDONLY);
  21. if (fd < 0) {
  22. perror(argv[1]);
  23. return EXIT_FAILURE;
  24. }
  25. if (argc == 3)
  26. size = atol(argv[2]);
  27. else {
  28. struct stat statbuf;
  29. if (fstat(fd, &statbuf) < 0) {
  30. perror(argv[1]);
  31. return EXIT_FAILURE;
  32. }
  33. if (statbuf.st_size > INT_MAX) {
  34. fprintf(stderr, "%s: Too big\n", argv[1]);
  35. return EXIT_FAILURE;
  36. }
  37. size = statbuf.st_size;
  38. }
  39. /* splice(2) file to stdout. */
  40. spliced = splice(fd, NULL, STDOUT_FILENO, NULL,
  41. size, SPLICE_F_MOVE);
  42. if (spliced < 0) {
  43. perror("splice");
  44. return EXIT_FAILURE;
  45. }
  46. close(fd);
  47. return EXIT_SUCCESS;
  48. }