comm.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini comm implementation for busybox
  4. *
  5. * Copyright (C) 2005 by Robert Sullivan <cogito.ergo.cogito@gmail.com>
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  8. */
  9. //usage:#define comm_trivial_usage
  10. //usage: "[-123] FILE1 FILE2"
  11. //usage:#define comm_full_usage "\n\n"
  12. //usage: "Compare FILE1 with FILE2\n"
  13. //usage: "\n -1 Suppress lines unique to FILE1"
  14. //usage: "\n -2 Suppress lines unique to FILE2"
  15. //usage: "\n -3 Suppress lines common to both files"
  16. #include "libbb.h"
  17. #define COMM_OPT_1 (1 << 0)
  18. #define COMM_OPT_2 (1 << 1)
  19. #define COMM_OPT_3 (1 << 2)
  20. /* writeline outputs the input given, appropriately aligned according to class */
  21. static void writeline(char *line, int class)
  22. {
  23. int flags = option_mask32;
  24. if (class == 0) {
  25. if (flags & COMM_OPT_1)
  26. return;
  27. } else if (class == 1) {
  28. if (flags & COMM_OPT_2)
  29. return;
  30. if (!(flags & COMM_OPT_1))
  31. putchar('\t');
  32. } else /*if (class == 2)*/ {
  33. if (flags & COMM_OPT_3)
  34. return;
  35. if (!(flags & COMM_OPT_1))
  36. putchar('\t');
  37. if (!(flags & COMM_OPT_2))
  38. putchar('\t');
  39. }
  40. puts(line);
  41. }
  42. int comm_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  43. int comm_main(int argc UNUSED_PARAM, char **argv)
  44. {
  45. char *thisline[2];
  46. FILE *stream[2];
  47. int i;
  48. int order;
  49. opt_complementary = "=2";
  50. getopt32(argv, "123");
  51. argv += optind;
  52. for (i = 0; i < 2; ++i) {
  53. stream[i] = xfopen_stdin(argv[i]);
  54. }
  55. order = 0;
  56. thisline[1] = thisline[0] = NULL;
  57. while (1) {
  58. if (order <= 0) {
  59. free(thisline[0]);
  60. thisline[0] = xmalloc_fgetline(stream[0]);
  61. }
  62. if (order >= 0) {
  63. free(thisline[1]);
  64. thisline[1] = xmalloc_fgetline(stream[1]);
  65. }
  66. i = !thisline[0] + (!thisline[1] << 1);
  67. if (i)
  68. break;
  69. order = strcmp(thisline[0], thisline[1]);
  70. if (order >= 0)
  71. writeline(thisline[1], order ? 1 : 2);
  72. else
  73. writeline(thisline[0], 0);
  74. }
  75. /* EOF at least on one of the streams */
  76. i &= 1;
  77. if (thisline[i]) {
  78. /* stream[i] is not at EOF yet */
  79. /* we did not print thisline[i] yet */
  80. char *p = thisline[i];
  81. writeline(p, i);
  82. while (1) {
  83. free(p);
  84. p = xmalloc_fgetline(stream[i]);
  85. if (!p)
  86. break;
  87. writeline(p, i);
  88. }
  89. }
  90. if (ENABLE_FEATURE_CLEAN_UP) {
  91. fclose(stream[0]);
  92. fclose(stream[1]);
  93. }
  94. return EXIT_SUCCESS;
  95. }