uniq.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <bio.h>
  12. typedef struct Who Who;
  13. struct Who
  14. {
  15. Who *next;
  16. char *line;
  17. char *name;
  18. };
  19. int cmp(const void *arg1, const void *arg2)
  20. {
  21. Who **a = (Who **)arg1;
  22. Who **b = (Who **)arg2;
  23. return strcmp((*a)->name, (*b)->name);
  24. }
  25. void
  26. main(int argc, char **argv)
  27. {
  28. int changed, i, n;
  29. Biobuf *b;
  30. char *p, *name;
  31. Who *first, *last, *w, *nw, **l;
  32. if(argc != 2){
  33. fprint(2, "usage: auth/uniq file\n");
  34. exits(0);
  35. }
  36. last = first = 0;
  37. b = Bopen(argv[1], OREAD);
  38. if(b == 0)
  39. exits(0);
  40. n = 0;
  41. changed = 0;
  42. while((p = Brdline(b, '\n')) != nil){
  43. p[Blinelen(b)-1] = 0;
  44. name = p;
  45. while(*p && *p != '|')
  46. p++;
  47. if(*p)
  48. *p++ = 0;
  49. for(nw = first; nw; nw = nw->next){
  50. if(strcmp(nw->name, name) == 0){
  51. free(nw->line);
  52. nw->line = strdup(p);
  53. changed = 1;
  54. break;
  55. }
  56. }
  57. if(nw)
  58. continue;
  59. w = malloc(sizeof(Who));
  60. if(w == 0){
  61. fprint(2, "auth/uniq: out of memory\n");
  62. exits(0);
  63. }
  64. memset(w, 0, sizeof(Who));
  65. w->name = strdup(name);
  66. w->line = strdup(p);
  67. if(first == 0)
  68. first = w;
  69. else
  70. last->next = w;
  71. last = w;
  72. n++;
  73. }
  74. Bterm(b);
  75. l = malloc(n*sizeof(Who*));
  76. for(i = 0, nw = first; nw; nw = nw->next, i++)
  77. l[i] = nw;
  78. qsort(l, n, sizeof(Who*), cmp);
  79. if(!changed)
  80. exits(0);
  81. b = Bopen(argv[1], OWRITE);
  82. if(b == 0){
  83. fprint(2, "auth/uniq: can't open %s\n", argv[1]);
  84. exits(0);
  85. }
  86. for(i = 0; i < n; i++)
  87. Bprint(b, "%s|%s\n", l[i]->name, l[i]->line);
  88. Bterm(b);
  89. }