Advertisement
Guest User

CP

a guest
Jan 21st, 2018
411
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.32 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdio.h>
  5. #include <fcntl.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8.  
  9. #define MAXLEN 1024
  10.  
  11. int nread;
  12. char str2[MAXLEN];
  13. char *stroki[MAXLEN];
  14. char data[MAXLEN];
  15. struct stat file_stat;
  16. int fd1, fd2;
  17.  
  18. void close_all(){
  19.     close(fd1);
  20.     close(fd2);
  21. }
  22.  
  23. int main(int argc, char ** argv){
  24.  
  25.  
  26.     if(argc > 3 || argc < 3){
  27.         perror("Illegal number of args");
  28.         return 0;
  29.     }
  30.  
  31.     char * arg1 = argv[1];
  32.     char * arg2 = argv[2];
  33.  
  34.     if(strcmp(arg1, arg2) == 0){
  35.         printf("%s\n", "Cannot copy file over itself");
  36.         return 0;
  37.     }
  38.  
  39.     fd1 = open(arg1, O_RDONLY);
  40.  
  41.     if(fd1 == -1){
  42.         perror("Error in opening first file");
  43.         close_all();
  44.         return 0;
  45.     }
  46.  
  47.     fd2 = open(arg2, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IWOTH | S_IXOTH);
  48.  
  49.     if(fd2 == -1){
  50.         perror("Error in opening second file");
  51.         close_all();
  52.         return 0;
  53.     }
  54.  
  55.     int res;
  56.  
  57.     while(res = read(fd1, &data, MAXLEN)){
  58.         if(res == -1){
  59.             perror("Error while reading from file");
  60.             close_all();
  61.             return 0;
  62.         }
  63.         printf("%d\n", res);
  64.         int resW = write(fd2, &data, res);
  65.         if(resW == -1){
  66.             perror("Error while writing to file");
  67.             close_all();
  68.             return 0;
  69.         }
  70.     }
  71.  
  72.     printf("%s\n", "Copy finished");
  73.     close_all();
  74.  
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement