2
0

rename.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #include <stdio.h>
  2. #include <fcntl.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <unistd.h>
  6. #include "test_helpers.h"
  7. static char oldpath[] = "old-name.out";
  8. static char newpath[] = "new-name.out";
  9. static char str[] = "Hello, World!";
  10. int main(void) {
  11. char buf[14] = { 0 };
  12. // Create old file
  13. int fd = creat(oldpath, 0777);
  14. ERROR_IF(creat, fd, == -1);
  15. UNEXP_IF(creat, fd, < 0);
  16. int written_bytes = write(fd, str, strlen(str));
  17. ERROR_IF(write, written_bytes, == -1);
  18. int c1 = close(fd);
  19. ERROR_IF(close, c1, == -1);
  20. UNEXP_IF(close, c1, != 0);
  21. // Rename old file to new file
  22. int rn_status = rename(oldpath, newpath);
  23. ERROR_IF(rename, rn_status, == -1);
  24. UNEXP_IF(rename, rn_status, != 0);
  25. // Read new file
  26. fd = open(newpath, O_RDONLY);
  27. ERROR_IF(open, fd, == -1);
  28. UNEXP_IF(open, fd, < 0);
  29. int read_bytes = read(fd, buf, strlen(str));
  30. ERROR_IF(read, read_bytes, == -1);
  31. UNEXP_IF(read, read_bytes, < 0);
  32. int c2 = close(fd);
  33. ERROR_IF(close, c2, == -1);
  34. UNEXP_IF(close, c2, != 0);
  35. // Remove new file
  36. int rm_status = remove(newpath);
  37. ERROR_IF(remove, rm_status, == -1);
  38. UNEXP_IF(remove, rm_status, != 0);
  39. // Compare file contents
  40. if (strcmp(str, buf) != 0) {
  41. puts("Comparison failed!");
  42. exit(EXIT_FAILURE);
  43. }
  44. }