使用 Lua FFI 写入文件

Write to file using Lua FFI

我正在尝试使用 Lua FFI using LuaJIT 将一些文本附加到文件中,但我对 C 语言不是很了解,所以我遇到了一些麻烦。这是代码:

local ffi = require "ffi"

ffi.cdef[[
typedef int __kernel_ssize_t;
typedef __kernel_ssize_t ssize_t;
ssize_t write(int fildes, const void *buf, size_t nbyte);
]]

local f = io.open("/tmp/test", "a+") -- Opening file in append mode

local message = "Hello World"
ffi.C.write(f, message, string.len(message))

f:close()

但我收到以下错误:

luajit: test.lua:12: bad argument #1 to 'write' (cannot convert 'void *' to 'int')
stack traceback:
    [C]: in function 'write'
    c.lua:12: in main chunk
    [C]: at 0x0100001490

我已经用下面的代码解决了这个问题:

local ffi = require "ffi"

ffi.cdef[[
typedef struct {
  char *fpos;
  void *base;
  unsigned short handle;
  short flags;
  short unget;
  unsigned long alloc;
  unsigned short buffincrement;
} FILE;

FILE *fopen(const char *filename, const char *mode);
int fprintf(FILE *stream, const char *format, ...);
int fclose(FILE *stream);
]]

local f = ffi.C.fopen("/tmp/test", "a+")
ffi.C.fprintf(f, "Hello World")
ffi.C.fclose(f)