SA-MP Forums Archive
How to load random file from folder? - Printable Version

+- SA-MP Forums Archive (https://sampforum.blast.hk)
+-- Forum: SA-MP Scripting and Plugins (https://sampforum.blast.hk/forumdisplay.php?fid=8)
+--- Forum: Scripting Help (https://sampforum.blast.hk/forumdisplay.php?fid=12)
+--- Thread: How to load random file from folder? (/showthread.php?tid=661544)



How to load random file from folder? - theralio - 07.12.2018

Hey

How to load a random file from a folder?


Re: How to load random file from folder? - Jefff - 07.12.2018

new random_file = random(MAX_EXISTED_FILES);
and create files as 0.txt, 1.txt ... ?


Re: How to load random file from folder? - theralio - 07.12.2018

the files have different names


Re: How to load random file from folder? - Calisthenics - 07.12.2018

An example using FileManager but it has to read once to retrieve how many files exist and a second to select the random one:
pawn Код:
new dir: dHandle, item[40], type, counter, random_file;
   
dHandle = dir_open("path_here");

while (dir_list(dHandle, item, type))
{
    if(type == FM_FILE) counter++;
}
       
dir_close(dHandle);

random_file = random(counter);
counter = 0;
dHandle = dir_open("path_here");

while (dir_list(dHandle, item, type))
{
    if(type == FM_FILE && counter++ == random_file) break;
}

dir_close(dHandle);
printf("random file: \"%s\"", item);
If you know the number of files will not exceed a certain amount, an array to store the file names and avoid the second loop is also a choice.


Re: How to load random file from folder? - theralio - 07.12.2018

and how can i do it that he only select .map files?


Re: How to load random file from folder? - Calisthenics - 08.12.2018

If there are files with different extensions in that directory, you will need to check the last 4 characters (matching .map).
pawn Код:
new dir: dHandle, item[40], type, counter, random_file;

dHandle = dir_open("./scriptfiles");

while (dir_list(dHandle, item, type))
{
    if(type == FM_FILE && strfind(item, ".map", true, strlen(item) - 4) != -1) counter++;
}

dir_close(dHandle);

random_file = random(counter);
counter = 0;
dHandle = dir_open("./scriptfiles");

while (dir_list(dHandle, item, type))
{
    if(type == FM_FILE && strfind(item, ".map", true, strlen(item) - 4) != -1 && counter++ == random_file) break;
}

dir_close(dHandle);
printf("random file: \"%s\"", item);
If you can, store all .map files in a folder called "Maps" or something else and you do not need strfind. The code from previous post will work.

Current random algorithm gives few results over and over again. If you want any map to have a chance, you may use MerRandom plugin.