uniq.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 = arg1, **b = arg2;
  22. return strcmp((*a)->name, (*b)->name);
  23. }
  24. void
  25. main(int argc, char **argv)
  26. {
  27. int changed, i, n;
  28. Biobuf *b;
  29. char *p, *name;
  30. Who *first, *last, *w, *nw, **l;
  31. if(argc != 2){
  32. fprint(2, "usage: auth/uniq file\n");
  33. exits(0);
  34. }
  35. last = first = 0;
  36. b = Bopen(argv[1], OREAD);
  37. if(b == 0)
  38. exits(0);
  39. n = 0;
  40. changed = 0;
  41. while(p = Brdline(b, '\n')){
  42. p[Blinelen(b)-1] = 0;
  43. name = p;
  44. while(*p && *p != '|')
  45. p++;
  46. if(*p)
  47. *p++ = 0;
  48. for(nw = first; nw; nw = nw->next){
  49. if(strcmp(nw->name, name) == 0){
  50. free(nw->line);
  51. nw->line = strdup(p);
  52. changed = 1;
  53. break;
  54. }
  55. }
  56. if(nw)
  57. continue;
  58. w = malloc(sizeof(Who));
  59. if(w == 0){
  60. fprint(2, "auth/uniq: out of memory\n");
  61. exits(0);
  62. }
  63. memset(w, 0, sizeof(Who));
  64. w->name = strdup(name);
  65. w->line = strdup(p);
  66. if(first == 0)
  67. first = w;
  68. else
  69. last->next = w;
  70. last = w;
  71. n++;
  72. }
  73. Bterm(b);
  74. l = malloc(n*sizeof(Who*));
  75. for(i = 0, nw = first; nw; nw = nw->next, i++)
  76. l[i] = nw;
  77. qsort(l, n, sizeof(Who*), cmp);
  78. if(!changed)
  79. exits(0);
  80. b = Bopen(argv[1], OWRITE);
  81. if(b == 0){
  82. fprint(2, "auth/uniq: can't open %s\n", argv[1]);
  83. exits(0);
  84. }
  85. for(i = 0; i < n; i++)
  86. Bprint(b, "%s|%s\n", l[i]->name, l[i]->line);
  87. Bterm(b);
  88. }