Tobiahao

S01_PLIKI_07

Jan 20th, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.49 KB | None | 0 0
  1. /*
  2. Napisz odpowiednik programu „cp” do kopiowania plików, bez obsługi katalogów i opcji wykonania.
  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.  
  12. #define BUFFER_SIZE 128
  13.  
  14. int main(int argc, char *argv[])
  15. {
  16.     if(argc != 3) {
  17.         fprintf(stderr, "Niepoprawna liczba argumentow!\nUzycie programu: %s [plik, ktory ma zostac skopiowany] [nowa nazwa/sciezka pliku]\n", argv[0]);
  18.         return EXIT_FAILURE;
  19.     }
  20.  
  21.     char *first_filename = argv[1];
  22.     char *second_filename = argv[2];
  23.     int first_fd, second_fd;
  24.     ssize_t status;
  25.     char buffer[BUFFER_SIZE];
  26.     ssize_t bytes_count = 0;
  27.  
  28.     if((first_fd = open(first_filename, O_RDONLY, 0600)) == -1) {
  29.         perror("open_first");
  30.         return EXIT_FAILURE;
  31.     }
  32.  
  33.     if((second_fd = open(second_filename, O_WRONLY | O_CREAT, 0600)) == -1) {
  34.         perror("open_second");
  35.         return EXIT_FAILURE;
  36.     }
  37.    
  38.     for(;;) {
  39.         status = read(first_fd, buffer, BUFFER_SIZE-1);
  40.         if(status == -1) {
  41.             perror("read");
  42.             return EXIT_FAILURE;
  43.         }
  44.         else if(status == 0) {
  45.             break;
  46.         }
  47.         else {
  48.             bytes_count += status;
  49.             if(write(second_fd, buffer, BUFFER_SIZE-1) == -1) {
  50.                 perror("write");
  51.                 return EXIT_FAILURE;
  52.             }      
  53.         }
  54.     }  
  55.  
  56.     printf("Skopiowano pomyslnie %ld bajtow!\n", bytes_count);
  57.  
  58.     if(close(second_fd) == -1) {
  59.         perror("close_second");
  60.         return EXIT_FAILURE;
  61.     }
  62.  
  63.     if(close(first_fd) == -1) {
  64.         perror("close_first");
  65.         return EXIT_FAILURE;
  66.     }
  67.  
  68.     return EXIT_SUCCESS;
  69. }
Add Comment
Please, Sign In to add comment