Grabbing random filenames from a directory

Hi,

If I had 100 text files all named the following.

1a
1b
1c
1d
2a
2b
2c ............

All the way up until there were 100 text files in the folder. How can I randomly grab one of those filenames? I dont need to fstream open the file or anything like that I just want to create a string from its filename. So.

String1 = (one of the filenames from the directory e.g. 7b)
String2 = (another filename from the directory that IS NOT the same as string1)

What would be the easiest/most efficient way of going about that ?
1) Obtain a list of the files in the folder
2) Generate a random number between 1 and 100
3) Find the name at that position in the list
4) Generate a second random number between 1 and 100
5) Find the name at that position in the list

How would I do "file removal" so if string 1 = 7b , string 2 cannot be 7b also
MikeyBoy said to "obtain a list" of the files.

Basically generate a list of strings that name all of your files. Randomly pick one of them out of the list, removing the name from the list as well.
To make the list;

Use FindFirstFile() to find "*.txt". The path of the file name is stored in the LPWIN32_FIND_DATA structure (cFileName). FindFirstFile also returns a handle that you use to continue the search in FindNextFile(). When you have finished the search the best practice is to call FindClose() because this closes the search handle.


FindFirstFile() -http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418%28v=vs.85%29.aspx

FindNextFile() - http://msdn.microsoft.com/en-us/library/windows/desktop/aa364428%28v=vs.85%29.aspx

FindClose() http://msdn.microsoft.com/en-us/library/windows/desktop/aa364413%28v=vs.85%29.aspx

DeleteFile() - http://msdn.microsoft.com/en-us/library/windows/desktop/aa363915%28v=vs.85%29.aspx

MoveFileEX() - http://msdn.microsoft.com/en-us/library/windows/desktop/aa365240%28v=vs.85%29.aspx

CopyFile() - http://msdn.microsoft.com/en-us/library/windows/desktop/aa363851%28v=vs.85%29.aspx

Full list of File Functions - http://msdn.microsoft.com/en-us/library/windows/desktop/aa364232%28v=vs.85%29.aspx
Last edited on
That's a Windows-specific way of doing it. For a more general, cross-platform approach, use the Boost filesystem utilities.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <windows.h>
#include <iostream>
#include <ctime>
#include <string>
#include <fstream>
#include <sstream>

int random(int min, int max) {
	static bool random=false;
	if(random==false) {
		random=true;
		srand(time(0));
	}
	return (min+(rand()%max));
}

int main(int argc, char** argv) {
	SetConsoleTitleA("Test");

	std::stringstream sstream;
	sstream << random(1, 100) << (char)(random(1, 4)+96);
	std::ifstream ifstream(sstream.str(), std::ios::binary);

	std::cin.get();
	return 0;
}


Also, my random function is borked somehow, but whatever.
Topic archived. No new replies allowed.