]>
Commit | Line | Data |
---|---|---|
1 | #include "reverse_lib.h" | |
2 | ||
3 | #include <err.h> | |
4 | #include <stdio.h> | |
5 | #include <stdlib.h> | |
6 | #include <string.h> | |
7 | #include <sysexits.h> | |
8 | #include <unistd.h> | |
9 | ||
10 | static const char test_file[] = "reverse.c"; | |
11 | ||
12 | char* reverse_to_temp_file(const char* input_file) { | |
13 | char* temp_filename = strdup("/tmp/reverse_test.XXXXXX"); | |
14 | int fd = mkstemp(temp_filename); | |
15 | if (fd == -1) err(EX_IOERR, "Couldn't make a temporary file"); | |
16 | FILE* f = fdopen(fd, "w"); | |
17 | if (f == NULL) err(EX_IOERR, "Couldn't open temporary file"); | |
18 | reverse_file(input_file, f); | |
19 | if (fclose(f) == EOF) err(EX_IOERR, "Couldn't close temporary file"); | |
20 | return temp_filename; | |
21 | } | |
22 | ||
23 | void test_reverse_twice_is_the_same() { | |
24 | char* intermediate = reverse_to_temp_file(test_file); | |
25 | char* back_to_normal = reverse_to_temp_file(intermediate); | |
26 | ||
27 | FILE* f1 = fopen(test_file, "r"); | |
28 | if (f1 == NULL) err(EX_IOERR, "Couldn't open test file"); | |
29 | FILE* f2 = fopen(back_to_normal, "r"); | |
30 | if (f2 == NULL) err(EX_IOERR, "Couldn't open twice-reversed temp file"); | |
31 | ||
32 | for (int pos = 0; ; pos++) { | |
33 | int c1 = fgetc(f1); | |
34 | int c2 = fgetc(f2); | |
35 | if (c1 == EOF && ferror(f1)) err(EX_IOERR, "Error reading test file"); | |
36 | if (c2 == EOF && ferror(f2)) err(EX_IOERR, "Error reading twice-reversed temp file"); | |
37 | if (c1 != c2) { | |
38 | errx(EX_SOFTWARE, "Unexpected difference found at offset %d after reversing twice. " | |
39 | "Expected %d but found %d", pos, c1, c2); | |
40 | } | |
41 | if (c1 == EOF) break; | |
42 | } | |
43 | ||
44 | if (fclose(f1) != 0) err(EX_IOERR, "Couldn't close test file"); | |
45 | if (fclose(f2) != 0) err(EX_IOERR, "Couldn't close twice-reversed temp file"); | |
46 | if (unlink(intermediate) == -1) err(EX_IOERR, "Couldn't remove intermediate temp file"); | |
47 | if (unlink(back_to_normal) == -1) err(EX_IOERR, "Couldn't remove twice-reversed temp file"); | |
48 | free(intermediate); | |
49 | free(back_to_normal); | |
50 | } | |
51 | ||
52 | int main() { | |
53 | test_reverse_twice_is_the_same(); | |
54 | puts("PASS"); | |
55 | return 0; | |
56 | } |