Tobiahao

S01_PLIKI_03

Jan 20th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.11 KB | None | 0 0
  1. /*
  2. Zademonstruj działanie funkcji replikującej deskryptory plików.
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <sys/types.h>
  8. #include <sys/stat.h>
  9. #include <fcntl.h>
  10. #include <unistd.h>
  11. #include <string.h>
  12.  
  13. #define BUFFER_SIZE 128
  14.  
  15. int main(int argc, char *argv[])
  16. {
  17.     char *filename = (char *)malloc(sizeof(strlen(argv[0]) + strlen(".c") + 1));
  18.     filename = strcat(argv[0], ".c");
  19.  
  20.     int first_fd, second_fd;
  21.     char buffer[BUFFER_SIZE];
  22.     int result;
  23.  
  24.     if((first_fd = open(filename, O_RDONLY | 0600)) == -1) {
  25.         perror("open");
  26.         return EXIT_FAILURE;
  27.     }
  28.  
  29.     if((second_fd = dup(first_fd)) == -1) {
  30.         perror("dup2");
  31.         return EXIT_FAILURE;
  32.     }
  33.  
  34.     printf("Odczytywanie pliku za pomoca skopiowanego deskryptora: \n");
  35.  
  36.     for(;;) {
  37.         memset(buffer, '\0', BUFFER_SIZE);
  38.         result = read(second_fd, buffer, BUFFER_SIZE-1);
  39.         if(result == -1) {
  40.             perror("read");
  41.             return EXIT_FAILURE;
  42.         }
  43.         else if(result == 0)
  44.             break;
  45.         else
  46.             printf("%s", buffer);
  47.     }
  48.  
  49.     printf("\n");
  50.  
  51.     if(close(first_fd) || close(second_fd)) {
  52.         perror("close");
  53.         return EXIT_FAILURE;
  54.     }
  55.  
  56.     return EXIT_SUCCESS;
  57. }
Add Comment
Please, Sign In to add comment