• Welcome to Valhalla Legends Archive.
 

Reading random line from a file

Started by warz, July 17, 2005, 09:17 PM

Previous topic - Next topic

warz

Which method would be best for a random quote idle message: saving quotes file to an array and pulling from the array, or reading a line from the file every time the idle message is sent?

I want the quotes.txt to be editable while the programing is running - so new quotes can be added. So maybe an array wouldn't be the easiest way? Wouldn't a large array, with a bunch of data in it also be memory consuming?

Just wondering what everyone thinks. Also, wasn't there a method of doing this in C++ on botdev.valhallalegeneds.com (wherever that site went)?

UserLoser.


warz

This might work a little bit better.


#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>

void SendRandomQuote(void);

int main(void) {
while(1){
SendRandomQuote();
Sleep(500);
}

return 0;
}

void SendRandomQuote(void) {
char *test[200];
    char buf[255];
    int i = 0, x = 0, y = 0;

    FILE *fp = fopen("Quotes.txt", "r");
    if (fp) {
           while (fgets(buf, sizeof(buf), fp)) {
                   test[i] = (char *)malloc(strlen(buf)+1);
                   strcpy(test[i], buf);
                   i++;
           }
    }
    for(x=0; x < i ; x++) {
            //printf("%s", test[x]);
    }
    //x = 0;

y = (GetTickCount() % x);

    printf("%s", test[y]);
}

Kp

Beware that warz's method will induce stack corruption if you have more than 200 quotes.
[19:20:23] (BotNet) <[vL]Kp> Any idiot can make a bot with CSB, and many do!

warz

Yeah, but if you've got more than 200 quotes also beware that you need to reduce your amount of quotes. ;-)

Mephisto

Quote from: warz on July 18, 2005, 09:20 PM
Yeah, but if you've got more than 200 quotes also beware that you need to reduce your amount of quotes. ;-)

That's stupid.  You should make your functions and designs generic whenever possible and above that non-error-prone which is blatantly obvious in your function.

warz

Quote from: Mephisto on July 18, 2005, 09:52 PM
Quote from: warz on July 18, 2005, 09:20 PM
Yeah, but if you've got more than 200 quotes also beware that you need to reduce your amount of quotes. ;-)

That's stupid.  You should make your functions and designs generic whenever possible and above that non-error-prone which is blatantly obvious in your function.

Uh, yeah, that's the idea.