Advertisement
Guest User

Untitled

a guest
Nov 14th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #include <string.h>
  5. #include <sys/stat.h>
  6.  
  7. #include <dirent.h>
  8. #include <unistd.h>
  9.  
  10. void copy_file(char *origin, char *dest)
  11. {
  12. FILE *input = fopen(origin, "r");
  13. FILE *output = fopen(dest, "w");
  14.  
  15. char content[256];
  16.  
  17. while (fgets(content, sizeof(content), input) != NULL)
  18. fputs(content, output);
  19. }
  20.  
  21. void copy_directory(char origin[], char dest[])
  22. {
  23. DIR *directory;
  24. struct dirent *contents = NULL;
  25.  
  26. struct stat dir = {0};
  27. short i;
  28.  
  29. if ((directory = opendir(origin)) == NULL) {
  30. fprintf(stderr, "couldn't open directory\n");
  31. exit(-1);
  32. }
  33.  
  34. if (stat(dest, &dir) != -1)
  35. chdir(dest);
  36.  
  37. else {
  38. mkdir(dest, 0777);
  39. chdir(dest);
  40. }
  41.  
  42. for (i = 1; i < strlen(contents->d_name); i++) {
  43. while ((contents = readdir(directory)) != NULL)
  44. copy_file(&contents->d_name[i], dest);
  45. }
  46.  
  47. closedir(directory);
  48. }
  49.  
  50. int main(int argc, char *argv[])
  51. {
  52. if (argc < 2) {
  53. fprintf(stderr, "Usage: cp [-r] origin dest\n");
  54. exit(-1);
  55. }
  56.  
  57. else {
  58. if (strncmp(argv[1], "-r", 2) == 0)
  59. copy_directory(argv[2], argv[3]);
  60.  
  61. else
  62. copy_file(argv[1], argv[2]);
  63. }
  64.  
  65. return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement