common_copy.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include "common.h"
  2. void copy_file(const char* input_path, const char* output_path, size_t size) {
  3. int fi = open_input_fd(input_path);
  4. printf("open(%zu) input OK\n", size);
  5. struct stat st;
  6. if (fstat(fi, &st) < 0)
  7. fatal_error("Failed to stat file %s: %s\n", input_path, strerror(errno));
  8. if (st.st_size != size)
  9. fatal_error("Size mismatch: expected %zu, got %zu\n", size, st.st_size);
  10. printf("fstat(%zu) input OK\n", size);
  11. int fo = open_output_fd(output_path, /*rdwr=*/false);
  12. printf("open(%zu) output OK\n", size);
  13. if (fstat(fo, &st) < 0)
  14. fatal_error("Failed to stat file %s: %s\n", output_path, strerror(errno));
  15. if (st.st_size != 0)
  16. fatal_error("Size mismatch: expected 0, got %zu\n", st.st_size);
  17. printf("fstat(%zu) output 1 OK\n", size);
  18. copy_data(fi, fo, input_path, output_path, size);
  19. if (fstat(fo, &st) < 0)
  20. fatal_error("Failed to stat file %s: %s\n", output_path, strerror(errno));
  21. if (st.st_size != size)
  22. fatal_error("Size mismatch: expected %zu, got %zu\n", size, st.st_size);
  23. printf("fstat(%zu) output 2 OK\n", size);
  24. close_fd(input_path, fi);
  25. printf("close(%zu) input OK\n", size);
  26. close_fd(output_path, fo);
  27. printf("close(%zu) output OK\n", size);
  28. }
  29. int main(int argc, char* argv[]) {
  30. if (argc < 3)
  31. fatal_error("Usage: %s <input_dir> <output_dir>\n", argv[0]);
  32. setup();
  33. char* input_dir = argv[1];
  34. char* output_dir = argv[2];
  35. // Process input directory
  36. DIR* dfd = opendir(input_dir);
  37. if (!dfd)
  38. fatal_error("Failed to open input directory %s: %s\n", input_dir, strerror(errno));
  39. printf("opendir(%s) OK\n", input_dir);
  40. struct dirent* de = NULL;
  41. while ((de = readdir(dfd)) != NULL) {
  42. printf("readdir(%s) OK\n", de->d_name);
  43. if (!strcmp(de->d_name, "."))
  44. continue;
  45. if (!strcmp(de->d_name, ".."))
  46. continue;
  47. // assume files have names that are their sizes as string
  48. size_t input_path_size = strlen(input_dir) + 1 + strlen(de->d_name) + 1;
  49. size_t output_path_size = strlen(output_dir) + 1 + strlen(de->d_name) + 1;
  50. char* input_path = alloc_buffer(input_path_size);
  51. char* output_path = alloc_buffer(output_path_size);
  52. size_t size = (size_t)strtoumax(de->d_name, NULL, 10);
  53. snprintf(input_path, input_path_size, "%s/%s", input_dir, de->d_name);
  54. snprintf(output_path, output_path_size, "%s/%s", output_dir, de->d_name);
  55. copy_file(input_path, output_path, size);
  56. free(input_path);
  57. free(output_path);
  58. }
  59. return 0;
  60. }