list all files in a folder

BlitzMax Forums/BlitzMax Beginners Area/list all files in a folder

julianbury(Posted 2007) [#1]
Hi people :-)

How can I list all the files in a folder and in all its subfolders to a text file?
I know this involves recursion.
I have never done recursion though and, although I think I know what it is, I do not know how to go about it.

Can anyone supply such a routine that I can learn from?

Thank you for your kind attention :-)

Julian (-_-)


grable(Posted 2007) [#2]
'
' note im writing to standard out here, but you can supply any kind of writable stream instead.
'
ListFiles( "C:/DoomLevels", StandardIOStream)

Function ListFiles( root:String, stream:TStream)
	Local dir:Int = ReadDir( root)
	If Not dir Then Return
	If Not root.EndsWith("/") Then root :+ "/"
	Repeat
		Local fn:String = NextFile(dir)
		If Not fn Then Exit ' <-- this is important, we dont want an endless loop
		If fn = ".." Then Continue
		If FileType( root + fn) = FILETYPE_FOLDER Then
			ListFiles( root + fn, stream) ' <-- recurse over this folder
		Else
			stream.WriteLine( root + fn)
		EndIf
	Forever
	CloseDir dir
EndFunction



julianbury(Posted 2007) [#3]
Hello Grable

Thank you, for this example.

I notice that you used forward-slashes for sub-directories.
Is this because you are in a Linux evironment?

I am in a Windows XP Pro enviroment - (for the games).
Should I change the forward-slashes to back-slashes?


grable(Posted 2007) [#4]
I used forward slashes out of preference, and it keeps the function slighty more portable.
blitzmax kan use both as it converts to the proper format for the platform (i havent tried mixing them though)

Btw, im on windows too ;)


gameshastra(Posted 2007) [#5]
Could you please tell me how to list only the specific type of files within a directory, such as .bmx only.


tonyg(Posted 2007) [#6]
Check ExtractExt$( path$ ) in your IDE.



Who was John Galt?(Posted 2007) [#7]
Stick this round the stream.writeline in Grables code:

if fn.endswith(".bmx")

endif

<I think endswith is the correct method name, check under strings in the bmx docs>


xlsior(Posted 2007) [#8]
Two corrections:

- First, the FILETYPE_FOLDER is not recognized by default, so using the actual value (2)
- Second, the examples above don't actually recurse folders properly (at least not on XP). The version below does.




grable(Posted 2007) [#9]
I guess i should have tested it properly before i posted it, now i am a little embarrassed.

This is how it was supposed to be ;)
Function ListFiles( root:String, stream:TStream)
	Local dir:Int = ReadDir( root)
	If Not dir Then Return
	If Not root.EndsWith("/") Then root :+ "/"
	Repeat
		Local fn:String = NextFile(dir)
		If Not fn Then Exit
		If fn = "." Or fn = ".." Then Continue
		If FileType( root + fn) = FILETYPE_DIR Then
			ListFiles( root + fn, stream)
		Else
			stream.WriteLine( root + fn)
		EndIf
	Forever
	CloseDir dir
EndFunction