/* C-style program use malloc()/realloc()/free(), stdio, and qsort() read or generate N strings optionally sort them I try to optimize it by reading char by char into a dynamically allocated buffer so that I eleminate the strcpy() and strlen(). - 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 no string buffer\n",file); FILE* fin = fopen(file,"r"); int c; int strmax = 8; int strcount = 0; char* p = (char*)malloc(strmax); while ((c=getc(fin))!=EOF) { // read: ignore chars on eof line if (c == '\n') { p[strcount] = 0; // terminate if (n==res) { res += res; buf = (char**)realloc(buf,sizeof(char*)*res); if (buf==0) quit(); } buf[n++] = p; strmax = 8; // start new string strcount = 0; p = (char*)malloc(strmax); } else { if (strcount==strmax-1) { // expand strmax += strmax; p = (char*)realloc(p,strmax); if (p==0) quit(); } p[strcount++] = c; } } } 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