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-19 10:51

>>$ ruby -ne 'l = $_ if rand < 1/$..to_f; END { puts l }' < /usr/share/dict/words

Ruby is such a piece of a shit. Look what that code does is for each line on line n chooses that line with a probability of 1/n. So for line 1  1/1, line 2: 1/2, line 3: 1/3 ...

Anyways when you sum up all the probabilities you find that it actually chooses a line uniformly randomly from a stream without the need to know the size before hand.

The reason why ruby is a shit eating fuck tard language is because that code doesn't explain any of this AT ALL.

here's some C pseudo code(make the routines readline and endofline).

 readline(fd,buf);
 strcpy(saved,buf);
 while(!endofline(fd)) {
   prob = 1.0/(++count);
   if (1.0*rand()/MAX_RANDOM <= prob) {
     strcpy(saved,buf);
   }
   readline(fd,buf);
 }
 puts(saved);

You know C is a pretty shit eating language too.


#!/bin/sh
awk "BEGIN {srand($RANDOM*$RANDOM);} {c = (rand() < (1.0 / FNR))?\$0:c} END { print c }" $*

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