avdl_file_op.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #include <unistd.h>
  2. #include <fcntl.h>
  3. #include <errno.h>
  4. #include <string.h>
  5. #include <sys/stat.h>
  6. #include <sys/types.h>
  7. #include <dirent.h>
  8. #include "avdl_file_op.h"
  9. int file_copy(const char *src, const char *dest, int append) {
  10. file_copy_at(0, src, 0, dest, append);
  11. return 0;
  12. }
  13. int file_copy_at(int src_at, const char *src, int dest_at, const char *dest, int append) {
  14. int s;
  15. if (src_at) {
  16. s = openat(src_at, src, O_RDONLY);
  17. }
  18. else {
  19. s = open(src, O_RDONLY);
  20. }
  21. if (!s) {
  22. printf("can't open %s: %s\n", src, strerror(errno));
  23. return -1;
  24. }
  25. int dest_flags = O_WRONLY | O_CREAT;
  26. if (append) dest_flags |= O_APPEND;
  27. int d;
  28. if (dest_at) {
  29. d = openat(dest_at, dest, dest_flags, S_IRUSR | S_IWUSR);
  30. }
  31. else {
  32. d = open(dest, dest_flags, S_IRUSR | S_IWUSR);
  33. }
  34. if (!d) {
  35. printf("can't open %s: %s\n", dest, strerror(errno));
  36. return -1;
  37. }
  38. char buffer[1024];
  39. int i = 0;
  40. ssize_t nread;
  41. while (nread = read(s, buffer, 1024), nread > 0) {
  42. if (write(d, buffer, nread) == -1) {
  43. printf("error: %s\n", strerror(errno));
  44. }
  45. i++;
  46. }
  47. close(s);
  48. close(d);
  49. return 0;
  50. }
  51. int dir_copy_recursive(int src_at, const char *src, int dst_at, const char *dst) {
  52. int src_dir;
  53. if (src_at) {
  54. src_dir = openat(src_at, src, O_DIRECTORY);
  55. }
  56. else {
  57. src_dir = open(src, O_DIRECTORY);
  58. }
  59. if (!src_dir) {
  60. printf("unable to open: %s\n", src);
  61. return -1;
  62. }
  63. DIR *d = fdopendir(src_dir);
  64. if (!d) {
  65. printf("unable to open dir: %s\n", src);
  66. return -1;
  67. }
  68. int dst_dir;
  69. if (dst_at) {
  70. dst_dir = openat(dst_at, dst, O_DIRECTORY);
  71. }
  72. else {
  73. dst_dir = open(dst, O_DIRECTORY);
  74. }
  75. if (!dst_at) {
  76. printf("unable to open: %s\n", dst);
  77. }
  78. struct dirent *dir;
  79. while ((dir = readdir(d)) != NULL) {
  80. if (strcmp(dir->d_name, ".") == 0
  81. || strcmp(dir->d_name, "..") == 0) {
  82. continue;
  83. }
  84. file_copy_at(src_dir, dir->d_name, dst_dir, dir->d_name, 0);
  85. }
  86. close(src_dir);
  87. close(dst_dir);
  88. closedir(d);
  89. return 0;
  90. }
  91. int dir_create(const char *filename) {
  92. mkdir(filename, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
  93. return 0;
  94. }