What's the best way to return a random line in a text file using C? It has to use the standard I/O library (<stdio.h>
) because it's for Nintendo DS homebrew.
Clarifications:
I was able to skip lines with scanf with the following instruction: fscanf(config_file, "%*[^\n]\n");
Read each line, and use a random number to choose whether to keep that line or ignore it. For the first line, you want odds of 1:1 to keep; for the second, you want odds of 1:2, etc.
count = 0;
while (fgets(line, length, stream) != NULL)
{
count++;
if ((rand() * count) / RAND_MAX == 0)
strcpy(keptline, line);
}
I haven't verified that this has the proper random qualities, but it seems right at first glance.
if ((rand() / (float)RAND_MAX) <= (1.0 / count))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With