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++.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 thelfstable 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.