使用Lua FFI将内容写入文件

我正在尝试使用LuaJIT使用Lua FFI将一些文本附加到文件中,但我对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

点赞
用户298406
用户298406

我使用以下代码解决了这个问题:

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)
2015-06-02 01:29:06