Recursive list of files on SD card with indexing
dirFile.open("/", ...) opens the root directory which always exist, even if there are no files.

You can check if there are files by checking openNext. If the first call returns false, there are no files or folders.

Some unrelated remarks:


Name variables you use, with more than 1 character (so e.g. numberOfFiles instead of n)
Do not increase a variable inside a Serial.print statement .. if you remove the 'test/debug' code, your sketch behaves differently.


Update:

I now see your question about the array. 300 is probably what you assume is the maximum number of files. Note that if 300 is passed, the sketch will crash.

What you can do to prevent this:


Easy solution: stop storing files after 300. In this case, make 300 a constant.
Solid solution: do not use a predetermined length array. However, this means some disadvantages:


You have to create a list structure and dynamically change the code.
This is slower (probably not an issue since SD card communication is much slower)
It can result in memory gaps, resulting in hard to solve memory problems later if the code is extended and more memory is needed.



I suggest you add some code, to stop storing at 300.