Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C - read a random line from a file.

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);
}

Name: Anonymous 2006-03-06 18:17

// select random position in the file
// if RAND_MAX < filesize then make sure enough rand()s are called to compensatefor (i=0;i<=fileSize/RAND_MAX;i++)
        currentPos += rand();
    currentPos %= fileSize;

FAIL for not just scaling it up or down

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List