Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 #define _GNU_SOURCE
0003 #include <errno.h>
0004 #include <fcntl.h>
0005 #include <limits.h>
0006 #include <stdio.h>
0007 #include <stdlib.h>
0008 #include <unistd.h>
0009 #include <sys/types.h>
0010 #include <sys/stat.h>
0011 
0012 int main(int argc, char *argv[])
0013 {
0014     int fd;
0015     size_t size;
0016     ssize_t spliced;
0017 
0018     if (argc < 2) {
0019         fprintf(stderr, "Usage: %s INPUT [BYTES]\n", argv[0]);
0020         return EXIT_FAILURE;
0021     }
0022 
0023     fd = open(argv[1], O_RDONLY);
0024     if (fd < 0) {
0025         perror(argv[1]);
0026         return EXIT_FAILURE;
0027     }
0028 
0029     if (argc == 3)
0030         size = atol(argv[2]);
0031     else {
0032         struct stat statbuf;
0033 
0034         if (fstat(fd, &statbuf) < 0) {
0035             perror(argv[1]);
0036             return EXIT_FAILURE;
0037         }
0038 
0039         if (statbuf.st_size > INT_MAX) {
0040             fprintf(stderr, "%s: Too big\n", argv[1]);
0041             return EXIT_FAILURE;
0042         }
0043 
0044         size = statbuf.st_size;
0045     }
0046 
0047     /* splice(2) file to stdout. */
0048     spliced = splice(fd, NULL, STDOUT_FILENO, NULL,
0049               size, SPLICE_F_MOVE);
0050     if (spliced < 0) {
0051         perror("splice");
0052         return EXIT_FAILURE;
0053     }
0054 
0055     close(fd);
0056     return EXIT_SUCCESS;
0057 }