Like the title says; how do I load every file in a directory? I'm interested in both c++ and lua.
Edit: For windows I'd be glad for some real working code and especially for lua. I can do with boost::filesystem for c++.
Like the title says; how do I load every file in a directory? I'm interested in both c++ and lua.
Edit: For windows I'd be glad for some real working code and especially for lua. I can do with boost::filesystem for c++.
Listing files in a directory is defined by the platform so you would have to use a platform dependent library. This is true of c++ and Lua (which implements only ansi c functionality).
For Lua, you want the module Lua Filesystem.
As observed by Nick, accessing the file system itself (as opposed to individual files) is outside the scope of the C and C++ standards. Since Lua itself is (with the exception of the dynamic loader used to implement require() for C modules) written in standard C, the core language lacks many file system features.
However, it is easy to extend the Lua core since (nearly) any platform that has a file system also supports DLLs or shared libraries. Lua File system is a portable library that adds support for directory iteration, file attribute discovery, and the like.
With lfs, emulating some of the capability of DIR in Lua is essentially as simple as:
Which produces output that looks like:
If your copy of Lua came from Lua for Windows, then you already have lfs installed, and the above sample will work out of the box.
Edit: Incidentally, the Lua solution might also be a sensible C or C++ solution. The Lua core is not at all large, provides a dynamic, garbage-collected language, and is easy to interact with from C either as a hosting application or as an extension module. To use lfs from a C application, you would link with the Lua DLL, initialize a Lua state, and get the state to execute the
require"lfs"
either vialuaL_dostring()
or by using the C API to retrieve therequire()
function from the global table, push the string"lfs"
, and call the Lua function with something likelua_pcall(L,1,1,0)
, which leaves thelfs
table on the top of the Lua stack.This approach probably makes the most sense if you already had a need for an embedded scripting language, and Lua meets your requirements.
For a C++ solution, have a look at the Boost.Filesystem library.