diff options
Diffstat (limited to 'pintos-progos/examples/cmp.c')
| -rw-r--r-- | pintos-progos/examples/cmp.c | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/pintos-progos/examples/cmp.c b/pintos-progos/examples/cmp.c new file mode 100644 index 0000000..94b406d --- /dev/null +++ b/pintos-progos/examples/cmp.c | |||
| @@ -0,0 +1,68 @@ | |||
| 1 | /* cat.c | ||
| 2 | |||
| 3 | Compares two files. */ | ||
| 4 | |||
| 5 | #include <stdio.h> | ||
| 6 | #include <syscall.h> | ||
| 7 | |||
| 8 | int | ||
| 9 | main (int argc, char *argv[]) | ||
| 10 | { | ||
| 11 | int fd[2]; | ||
| 12 | |||
| 13 | if (argc != 3) | ||
| 14 | { | ||
| 15 | printf ("usage: cmp A B\n"); | ||
| 16 | return EXIT_FAILURE; | ||
| 17 | } | ||
| 18 | |||
| 19 | /* Open files. */ | ||
| 20 | fd[0] = open (argv[1]); | ||
| 21 | if (fd[0] < 0) | ||
| 22 | { | ||
| 23 | printf ("%s: open failed\n", argv[1]); | ||
| 24 | return EXIT_FAILURE; | ||
| 25 | } | ||
| 26 | fd[1] = open (argv[2]); | ||
| 27 | if (fd[1] < 0) | ||
| 28 | { | ||
| 29 | printf ("%s: open failed\n", argv[1]); | ||
| 30 | return EXIT_FAILURE; | ||
| 31 | } | ||
| 32 | |||
| 33 | /* Compare data. */ | ||
| 34 | for (;;) | ||
| 35 | { | ||
| 36 | int pos; | ||
| 37 | char buffer[2][1024]; | ||
| 38 | int bytes_read[2]; | ||
| 39 | int min_read; | ||
| 40 | int i; | ||
| 41 | |||
| 42 | pos = tell (fd[0]); | ||
| 43 | bytes_read[0] = read (fd[0], buffer[0], sizeof buffer[0]); | ||
| 44 | bytes_read[1] = read (fd[1], buffer[1], sizeof buffer[1]); | ||
| 45 | min_read = bytes_read[0] < bytes_read[1] ? bytes_read[0] : bytes_read[1]; | ||
| 46 | if (min_read == 0) | ||
| 47 | break; | ||
| 48 | |||
| 49 | for (i = 0; i < min_read; i++) | ||
| 50 | if (buffer[0][i] != buffer[1][i]) | ||
| 51 | { | ||
| 52 | printf ("Byte %d is %02hhx ('%c') in %s but %02hhx ('%c') in %s\n", | ||
| 53 | pos + i, | ||
| 54 | buffer[0][i], buffer[0][i], argv[1], | ||
| 55 | buffer[1][i], buffer[1][i], argv[2]); | ||
| 56 | return EXIT_FAILURE; | ||
| 57 | } | ||
| 58 | |||
| 59 | if (min_read < bytes_read[1]) | ||
| 60 | printf ("%s is shorter than %s\n", argv[1], argv[2]); | ||
| 61 | else if (min_read < bytes_read[0]) | ||
| 62 | printf ("%s is shorter than %s\n", argv[2], argv[1]); | ||
| 63 | } | ||
| 64 | |||
| 65 | printf ("%s and %s are identical\n", argv[1], argv[2]); | ||
| 66 | |||
| 67 | return EXIT_SUCCESS; | ||
| 68 | } | ||
