Posted by
| Nick Gammon
Australia (23,120 posts) Bio
Forum Administrator |
Message
| In case anyone wants to incorporate the code I used into their own projects, here it is ...
#include "../lua/lua.h"
#include "../lua/lauxlib.h"
#include <io.h>
#include <errno.h>
// make number table item
static void MakeNumberTableItem (lua_State *L, const char * name, const double n)
{
lua_pushstring (L, name);
lua_pushnumber (L, n);
lua_rawset(L, -3);
}
// make boolean table item
static void MakeBoolTableItem (lua_State *L, const char * name, const int b)
{
if (b)
{
lua_pushstring (L, name);
lua_pushboolean (L, b != 0);
lua_rawset(L, -3);
}
}
static int getdirectory (lua_State *L)
{
// get directory name (eg. C:\mushclient\*.doc)
size_t dirLength;
const char * dirname = luaL_checklstring (L, 1, &dirLength);
struct _finddatai64_t fdata;
int h = _findfirsti64 (dirname, &fdata); // get handle
if (h == -1L) // no good?
{
lua_pushnil (L);
switch (errno)
{
case EINVAL: lua_pushstring (L, "Invalid filename specification"); break;
default: lua_pushstring (L, "File specification could not be matched"); break;
}
return 2; // return nil, error message
}
lua_newtable(L); // table of entries
do
{
lua_pushstring (L, fdata.name); // file name (will be key)
lua_newtable(L); // table of attributes
// inside this new table put the file attributes
MakeNumberTableItem (L, "size", (double) fdata.size);
if (fdata.time_create != -1) // except FAT
MakeNumberTableItem (L, "create_time", fdata.time_create);
if (fdata.time_access != -1) // except FAT
MakeNumberTableItem (L, "access_time", fdata.time_access);
MakeNumberTableItem (L, "write_time", fdata.time_write);
MakeBoolTableItem (L, "archive", fdata.attrib & _A_ARCH);
MakeBoolTableItem (L, "hidden", fdata.attrib & _A_HIDDEN);
MakeBoolTableItem (L, "normal", fdata.attrib & _A_NORMAL);
MakeBoolTableItem (L, "readonly", fdata.attrib & _A_RDONLY);
MakeBoolTableItem (L, "directory", fdata.attrib & _A_SUBDIR);
MakeBoolTableItem (L, "system", fdata.attrib & _A_SYSTEM);
lua_rawset(L, -3); // set key of table item (ie. file name)
} while (_findnexti64 ( h, &fdata ) == 0);
_findclose (h);
return 1; // one table of entries
} // end of getdirectory
// table of operations
static const struct luaL_reg utilslib [] =
{
{"readdir", getdirectory},
{NULL, NULL}
};
// register library
LUALIB_API int luaopen_compress(lua_State *L)
{
luaL_openlib(L, "utils", utilslib, 0);
return 1;
}
|
- Nick Gammon
www.gammon.com.au, www.mushclient.com | Top |
|