read_write.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include "common.h"
  2. void read_write(const char* file_path) {
  3. const size_t size = 1024 * 1024;
  4. int fd = open_output_fd(file_path, /*rdwr=*/true);
  5. printf("open(%s) RW OK\n", file_path);
  6. void* buf1 = alloc_buffer(size);
  7. void* buf2 = alloc_buffer(size);
  8. fill_random(buf1, size);
  9. write_fd(file_path, fd, buf1, size);
  10. printf("write(%s) RW OK\n", file_path);
  11. seek_fd(file_path, fd, 0, SEEK_SET);
  12. printf("seek(%s) RW OK\n", file_path);
  13. read_fd(file_path, fd, buf2, size);
  14. printf("read(%s) RW OK\n", file_path);
  15. if (memcmp(buf1, buf2, size) != 0)
  16. fatal_error("Read data is different from what was written\n");
  17. printf("compare(%s) RW OK\n", file_path);
  18. for (size_t i = 0; i < 1024; i++) {
  19. size_t offset = rand() % (size - 1024);
  20. size_t chunk_size = rand() % 1024;
  21. fill_random(buf1, chunk_size);
  22. seek_fd(file_path, fd, offset, SEEK_SET);
  23. write_fd(file_path, fd, buf1, chunk_size);
  24. seek_fd(file_path, fd, offset, SEEK_SET);
  25. read_fd(file_path, fd, buf2, chunk_size);
  26. if (memcmp(buf1, buf2, chunk_size) != 0)
  27. fatal_error("Chunk data is different from what was written (offset %zu, size %zu)\n", offset, chunk_size);
  28. }
  29. close_fd(file_path, fd);
  30. printf("close(%s) RW OK\n", file_path);
  31. free(buf1);
  32. free(buf2);
  33. }
  34. int main(int argc, char* argv[]) {
  35. if (argc < 2)
  36. fatal_error("Usage: %s <file_path>\n", argv[0]);
  37. setup();
  38. read_write(argv[1]);
  39. return 0;
  40. }