#include #include #include struct PS { char * uname; char * fullname; }; struct PS * newPS(char * a, char * b) { struct PS * n = (struct PS *)malloc(sizeof(struct PS)); n->uname = a; n->fullname = b; return n; } struct VecPS { struct PS * * data; int cap, num; }; struct VecPS * newVecPS(void) { struct VecPS * n = (struct VecPS *)malloc(sizeof(struct VecPS)); n->data = NULL; n->cap = 0; n->num = 0; return n; } void delete(struct VecPS * v) { int i; for (i = 0; i < v->num; i += 1) { struct PS * p = v->data[i]; free(p->uname); free(p->fullname); free(p); } free(v); } void enlarge(struct VecPS * v) { int newcap = v->cap * 2; if (newcap == 0) newcap = 1; struct PS * * newdata = (struct PS * *)malloc(sizeof(struct PS *)*newcap); int i; for (i = 0; i < v->num; i += 1) newdata[i] = v->data[i]; free(v->data); v->data = newdata; v->cap = newcap; } void add(struct VecPS * v, struct PS * p) { if (v->num >= v->cap) enlarge(v); v->data[v->num] = p; v->num += 1; } void sort(struct PS * * array, int size) { int begin, i; for (begin = 0; begin < size-1; begin += 1) { int smp = begin; for (i = begin+1; i < size; i += 1) if (strcmp(array[i]->uname, array[smp]->uname) < 0) smp = i; struct PS * temp = array[begin]; array[begin] = array[smp]; array[smp] = temp; } } int compa(const void *a, const void * b) { struct PS * pa = * (struct PS * *) a; struct PS * pb = * (struct PS * *) b; return strcmp(pa->uname, pb->uname); } int main() { FILE * f = fopen("/etc/passwd", "r"); if (f == NULL) { fprintf(stderr, "DCan't open /etc/passwd\n"); exit(1); } char line[1000]; struct VecPS * v = newVecPS(); while (1) { char * s = fgets(line, sizeof(line), f); if (s == NULL) break; int len = strlen(line); if (line[len-1] != '\n') { fprintf(stderr, "line is too long\n"); exit(1); } if (line[0] == '#') continue; char * p1 = strtok(line, ":\n"); if (p1 == NULL) continue; char * p2 = strtok(NULL, ":\n"); char * p3 = strtok(NULL, ":\n"); char * p4 = strtok(NULL, ":\n"); char * p5 = strtok(NULL, ":\n"); if (p5 == NULL) { fprintf(stderr, "%s hasn't enough fields in /etc/passwd\n", p1); exit(1); } struct PS * p = newPS(strdup(p1), strdup(p5)); add(v, p); } // sort(v->data, v->num); qsort(v->data, v->num, sizeof(struct PS *), compa); int i; for (i=0; i < v->num; i += 1) { struct PS * p = v->data[i]; printf("%s is %s\n", p->uname, p->fullname); } delete(v); fclose(f); }