Name: Anonymous 2006-03-06 10:31
dear world4chan, I wrote this to return a random line read from a file, but I hate it. what would you do?
#define MAX_LINE_SIZE 1024
void readQuote(int sock_desc)
{
//data
FILE* quoteSource; //source file pointer
int numLines; //max number of lines
int rndLine; //random line
int i;
char buff[MAX_LINE_SIZE] = {0};
//initialize the random number generator
srand(time(NULL));
//open file; check for errors
quoteSource = fopen("quotes.txt", "r");
if (quoteSource == NULL)
{
printf("!! Error accessing file.\n");
return;
}
//get the file size, if zero, exit
numLines = 0;
while (!feof(quoteSource))
if (fgetc(quoteSource) == '\n') numLines++;
rewind(quoteSource);
if (numLines == 0)
{
printf("!! Quote file empty\n");
fclose(quoteSource);
return;
}
//select a line and read until that line is found
rndLine = (rand() % numLines) + 1;
printf("line %d of %d: ", rndLine, numLines);
for (i = 0; i < rndLine; i++)
fgets(buff, MAX_LINE_SIZE, quoteSource);
printf("%s\n", buff);
fclose(quoteSource);
}
#define MAX_LINE_SIZE 1024
void readQuote(int sock_desc)
{
//data
FILE* quoteSource; //source file pointer
int numLines; //max number of lines
int rndLine; //random line
int i;
char buff[MAX_LINE_SIZE] = {0};
//initialize the random number generator
srand(time(NULL));
//open file; check for errors
quoteSource = fopen("quotes.txt", "r");
if (quoteSource == NULL)
{
printf("!! Error accessing file.\n");
return;
}
//get the file size, if zero, exit
numLines = 0;
while (!feof(quoteSource))
if (fgetc(quoteSource) == '\n') numLines++;
rewind(quoteSource);
if (numLines == 0)
{
printf("!! Quote file empty\n");
fclose(quoteSource);
return;
}
//select a line and read until that line is found
rndLine = (rand() % numLines) + 1;
printf("line %d of %d: ", rndLine, numLines);
for (i = 0; i < rndLine; i++)
fgets(buff, MAX_LINE_SIZE, quoteSource);
printf("%s\n", buff);
fclose(quoteSource);
}