cmp.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* SPDX-License-Identifier: BSD-3-Clause */
  2. /*
  3. * Copyright (C) 2022, 2023 Ferass El Hafidi <vitali64pmemail@protonmail.com>
  4. */
  5. #include <stdio.h>
  6. #include <unistd.h>
  7. #include <string.h>
  8. #include <errno.h>
  9. /* Requirements in common.h */
  10. #define REQ_PRINT_USAGE
  11. #define REQ_ERRPRINT
  12. #include "../common/common.h"
  13. #define DESCRIPTION "Compare two files."
  14. #define OPERANDS "[-l|-s] file1 file2"
  15. int main(int argc, char *argv[]) {
  16. FILE *file1, *file2;
  17. int argument, char_pos = 1, line_pos = 1, param_l, param_s, differ;
  18. char *argv0 = strdup(argv[0]), ch1, ch2;
  19. while ((argument = getopt(argc, argv, "ls")) != -1) {
  20. if (argument == '?')
  21. return print_usage(argv0, DESCRIPTION, OPERANDS, VERSION);
  22. else if (argument == 'l') param_l = 1;
  23. else if (argument == 's') param_s = 1;
  24. } argc -= optind; argv += optind;
  25. if (argc != 2) return print_usage(argv0, DESCRIPTION, OPERANDS, VERSION);
  26. /* Open the files. */
  27. file1 = fopen(argv[0], "r");
  28. file2 = fopen(argv[1], "r");
  29. if (file1 == NULL)
  30. return errprint(argv0, argv[0], errno);
  31. else if (file2 == NULL)
  32. return errprint(argv0, argv[1], errno);
  33. /* Compare! */
  34. while ((ch1 = fgetc(file1)) && (ch2 = fgetc(file2))) {
  35. if (ch1 == -1 || ch2 == -1) {
  36. return errprint(argv0, "fgetc()", errno);
  37. } else if (ch1 != ch2) {
  38. differ = 1;
  39. if (param_l)
  40. printf("%d %o %o\n", char_pos, ch1, ch2);
  41. else if (!param_s)
  42. printf("%s %s differ: char %d, line %d\n", argv[0], argv[1],
  43. char_pos, line_pos);
  44. if (!param_l) break;
  45. }
  46. if (ch1 == '\n' && ch2 == '\n')
  47. line_pos++;
  48. char_pos++;
  49. }
  50. return differ;
  51. }