82 lines
2.1 KiB
C++
82 lines
2.1 KiB
C++
#include "lib.h"
|
|
#include <filesystem>
|
|
#include <iostream>
|
|
|
|
namespace fs = std::filesystem;
|
|
|
|
static const luaL_Reg lua_fs[] = {
|
|
{"file_exists", file_exists}, {"is_regular_file", is_regular_file}, {"copy_file", copy_file},
|
|
{"delete_file", delete_file}, {"get_dir_files", get_dir_files}, {NULL, NULL}};
|
|
|
|
int file_exists(lua_State* L)
|
|
{
|
|
const char* path = luaL_checkstring(L, 1);
|
|
bool result = fs::exists(path);
|
|
lua_pushboolean(L, result);
|
|
return 1;
|
|
}
|
|
|
|
/// @brief 文件是否是一个常规文件
|
|
/// @param path 文件路径
|
|
/// @return
|
|
int is_regular_file(lua_State* L)
|
|
{
|
|
const char* path = luaL_checkstring(L, 1);
|
|
bool result = fs::is_regular_file(path);
|
|
lua_pushboolean(L, result);
|
|
return 1;
|
|
}
|
|
|
|
/// @brief 复制文件
|
|
/// @param source 源文件(string)
|
|
/// @param destination 目标文件(string)
|
|
/// @return bool
|
|
int copy_file(lua_State* L)
|
|
{
|
|
const char* source = luaL_checkstring(L, 1);
|
|
const char* destination = luaL_checkstring(L, 2);
|
|
bool result = fs::copy_file(source, destination);
|
|
lua_pushboolean(L, result);
|
|
return 1;
|
|
}
|
|
|
|
int delete_file(lua_State* L)
|
|
{
|
|
const char* path = luaL_checkstring(L, 1);
|
|
bool result = fs::remove(path);
|
|
lua_pushboolean(L, result);
|
|
return 1;
|
|
}
|
|
|
|
int luaopen_lua_fs(lua_State* L)
|
|
{
|
|
luaL_newlib(L, lua_fs);
|
|
return 1;
|
|
}
|
|
|
|
int get_dir_files(lua_State* L)
|
|
{
|
|
// 获取第一个参数:目录路径
|
|
const char* dir_path = luaL_checkstring(L, 1);
|
|
|
|
// 检查目录是否存在
|
|
if (!fs::exists(dir_path) || !fs::is_directory(dir_path)) {
|
|
lua_pushnil(L);
|
|
lua_pushstring(L, "Invalid directory path");
|
|
return 2; // 返回 nil 和错误信息
|
|
}
|
|
|
|
// 创建一个新的 Lua 表用于存放文件列表
|
|
lua_newtable(L);
|
|
int table_index = lua_gettop(L); // 获取当前 Lua 表的位置
|
|
|
|
int index = 1;
|
|
for (const auto& entry : fs::directory_iterator(dir_path)) {
|
|
if (fs::is_regular_file(entry.status())) {
|
|
lua_pushstring(L, entry.path().filename().string().c_str());
|
|
lua_rawseti(L, table_index, index);
|
|
index++;
|
|
}
|
|
}
|
|
return 1;
|
|
} |