Valhalla Legends Forums Archive | C/C++ Programming | Reading random line from a file

AuthorMessageTime
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)?
July 18, 2005, 2:17 AM
UserLoser.
[quote author=warz link=topic=12262.msg121110#msg121110 date=1121653046]
Also, wasn't there a method of doing this in C++ on botdev.valhallalegeneds.com (wherever that site went)?
[/quote]

Somewhat.
July 18, 2005, 3:44 AM
warz
This might work a little bit better.

[code]
#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]);
}
[/code]
July 18, 2005, 4:24 AM
Kp
Beware that warz's method will induce stack corruption if you have more than 200 quotes.
July 19, 2005, 2:07 AM
warz
Yeah, but if you've got more than 200 quotes also beware that you need to reduce your amount of quotes. ;-)
July 19, 2005, 2:20 AM
Mephisto
[quote author=warz link=topic=12262.msg121180#msg121180 date=1121739643]
Yeah, but if you've got more than 200 quotes also beware that you need to reduce your amount of quotes. ;-)
[/quote]

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.
July 19, 2005, 2:52 AM
warz
[quote author=Mephisto link=topic=12262.msg121183#msg121183 date=1121741578]
[quote author=warz link=topic=12262.msg121180#msg121180 date=1121739643]
Yeah, but if you've got more than 200 quotes also beware that you need to reduce your amount of quotes. ;-)
[/quote]

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.
[/quote]

Uh, yeah, that's the idea.
July 19, 2005, 11:42 AM

Search