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:
require "lfs"
dot = arg[1] or "."
for name in lfs.dir(dot) do
local fqn = dot.."/"..name
local attr = lfs.attributes(fqn)
print(name, attr.mode, os.date("%Y-%m-%d %H:%M",attr.modification), attr.size)
end
Which produces output that looks like:
E:...>t-lfs.lua
. directory 2009-04-02 13:23 0
.. directory 2009-04-02 13:18 0
foo.txt file 2009-02-23 01:56 0
t-lfs.lua file 2009-04-02 13:18 241
E:...>
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 via luaL_dostring()
or by using the C API to retrieve the require()
function from the global table, push the string "lfs"
, and call the Lua function with something like lua_pcall(L,1,1,0)
, which leaves the lfs
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.