Quipex

lab3

Apr 9th, 2017
414
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.97 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/stat.h>
  4. #include <sys/types.h>
  5. #include <fcntl.h>
  6. #include <unistd.h>
  7. #include <sys/mman.h>
  8. #include <errno.h>
  9.  
  10. int main(int argc, char* argv[]){
  11.     struct stat sb;
  12.     off_t len;
  13.     char *fp;
  14.     int fd;
  15.  
  16.     if (argc < 2){
  17.         fprintf(stderr, "usage: %s file1 [file2...]\n", argv[0]);
  18.         exit(1);
  19.     }
  20.  
  21.     for (int i = 1; i < argc; ++i)
  22.     {
  23.         fd = open (argv[i], O_RDONLY);
  24.         if(fd == -1){
  25.             perror("open");
  26.             exit(2);
  27.         }
  28.  
  29.         if (fstat (fd, &sb) == -1){
  30.             perror("fstat");
  31.             exit(3);
  32.         }
  33.  
  34.         if(!S_ISREG (sb.st_mode)){
  35.             fprintf(stderr, "%s is not a file\n", argv[i]);
  36.             exit(4);
  37.         }
  38.  
  39.         fp = mmap (0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
  40.         if (fp == MAP_FAILED){
  41.             perror("mmap");
  42.             exit(5);
  43.         }
  44.  
  45.         if (close(fd) == -1){
  46.             perror("close");
  47.             exit(6);
  48.         }
  49.  
  50.         write(STDOUT_FILENO, fp, sb.st_size);
  51.         putchar('\n');
  52.  
  53.         if(munmap (fp, sb.st_size)==-1){
  54.             perror("munmap");
  55.             exit(7);
  56.         }
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment