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-23 18:00

>>32

I do enjoy scat, but that isn't what you meant. 

When you sir go to linux user group meetings you buy beer and cigarettes. Before arriving home after another awesome LUG meeting you pour the beer all over yourself and surrounds yourself with burning cigarettes in order to convince your parents that you do have a social life. Sometimes you apply lipstick to your hand and gives yourself kisses.

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