/* C-style program use malloc()/realloc()/free(), stdio, and qsort() read or generate N strings optionally sort them - Bjarne Stroustrup - http://www.research.att/~bs */ #include #include #include int cmp(const void* p, const void* q) { return strcmp(*(char**)p,*(char**)q); } void quit() { fprintf(stderr,"memory exhausted\n"); exit(1); } /* command line argument handling: prog 1 - read from cin and sort prog 0 - read from cin (don't sort) prog 1 file - read from file and sort prog 0 file - read from file (don't sort) prog 1 file ofile - read from file, sort, and write to ofile prog 0 file ofile - read from file (don't sort) and write to ofile an optional 4th argument controls preallocation. */ int main(int argc, char* argv[]) { int max = 0; // by default: read from cin int res = 1000; // by default: grow incrementally bool s = true; // by default: sort char* file = 0; char* ofile = 0; switch (argc) { // s { max | file } ofile res case 5: res = atoi(argv[4]); case 4: ofile = argv[3]; case 3: max = atoi(argv[2]); if (max == 0) file = argv[2]; case 2: s = atoi(argv[1]); break; default: fprintf(stderr,"wrong number of arguments\n"); exit(1); } char** buf = (char**)malloc(sizeof(char*)*res); if (buf==0) quit(); const int maxline = 2000; char d[maxline]; int n = 0; // number of elements if (max) { printf("generate %d\n",max); } else if (file) { printf("C style read from %s using string buffer\n",file); FILE* fin = fopen(file,"r"); while (fscanf(fin,"%s",&d)==1) { // read char* p = (char*)malloc(strlen(d)+1); // strdup() isn't standard if (p==0) quit(); strcpy(p,d); if (n==res) { res += res; buf = (char**)realloc(buf,sizeof(char*)*res); if (buf==0) quit(); } buf[n++] = p; } } else { printf("read stdin\n"); } if (s) { printf("qsort(%p,%d,%d,%p)\n",buf, n, sizeof(char*), strcmp); qsort(buf, n, sizeof(char*), cmp); } if (ofile) { printf("write %s\n",ofile); FILE* fout = fopen(ofile,"w"); for (int i = 0; i