/* Get a random line from a text file and display it to to stdout. The file should, for now, be named "test2.txt"...we'll change that later to make it accept a command line option. */ #include #include #include enum {SUCCESS, FAIL, MAX_LEN = 4000}; main(void) { FILE *fptr, *fptr2; char filename[] = "test2.txt"; int reval = SUCCESS; /* Initialize the randomness thing */ time_t now; time(&now); srand(now); /* Rand should be ready */ /* Can we open the file? */ if ((fptr = fopen(filename, "r")) == NULL ) { printf("Can't open %s for reading.\n", filename); reval = FAIL; } else { /* Apparently we can open the file Set up the stuff. */ char buff[MAX_LEN]; int c = 0; int d = 0; int j; /* This counts the lines in the file... Surely there's a better way to do this than reading the entire file and then re-reading it. Ask Steve */ while (fgets(buff, MAX_LEN, fptr) !=NULL) { d++; } fclose(fptr); /* Okay...gimme a random line of the file. */ j=rand()%d+1; /* Sigh..._reopen_ the file. Again, there's gotta be a better way. */ fptr2 = fopen(filename, "r"); while (fgets(buff, MAX_LEN, fptr2) != NULL) { c++; if (c == j) { printf("%s" , buff); } } fclose(fptr2); return reval; } }