03.04.2013, 16:53
Two questions:
If I have a file with 50 lines, and I want to know how many lines there are, apart from looping through them or storing the number of lines somewhere (perhaps in the file itself), what can I do?
If I want to read line 15 from the file, what do I do?
I've been looking on the wiki and in file.inc itself but it doesn't seem to have these capabilities? I thought perhaps fseek() could be used for this, but that only works for individual characters - not lines.
EDIT: Well, I've made this:
But I'm still wondering if there's a better way! I had to do strdel() because this weird thing happened where there would be a new line after the string.
This could need to be called 100+ times in a single moment, so efficiency matters here.
I benchmarked this with 100 iterations (the maximum that will ever be needed at one moment) with this line repeated 100 times in a file: '1234.5678, 1234.5678, 1234.5678, 180.0' and it took 600 MS. Not TOO bad I guess, but still I'd like to make this more efficient. I guess using format() isn't a great idea, but I'm not sure how else to do the string. Perhaps returning the string would be better.
If I have a file with 50 lines, and I want to know how many lines there are, apart from looping through them or storing the number of lines somewhere (perhaps in the file itself), what can I do?
If I want to read line 15 from the file, what do I do?
I've been looking on the wiki and in file.inc itself but it doesn't seem to have these capabilities? I thought perhaps fseek() could be used for this, but that only works for individual characters - not lines.
EDIT: Well, I've made this:
pawn Code:
stock ReadFileRandomLine(filename[], dest[], dest_size)
{
new File:file = fopen(filename, io_read);
new str[256], lines;
while(fread(file, str)) lines++;
new line = random(lines);
fseek(file, 0);
for(new i=0; i<line; i++) fread(file, str);
format(dest, dest_size, "%s", str);
strdel(dest, strlen(dest)-1, strlen(dest));
fclose(file);
return 1;
}
This could need to be called 100+ times in a single moment, so efficiency matters here.
I benchmarked this with 100 iterations (the maximum that will ever be needed at one moment) with this line repeated 100 times in a file: '1234.5678, 1234.5678, 1234.5678, 180.0' and it took 600 MS. Not TOO bad I guess, but still I'd like to make this more efficient. I guess using format() isn't a great idea, but I'm not sure how else to do the string. Perhaps returning the string would be better.