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