Search code examples
fileluaffiluajit

Write to file using Lua FFI


I am trying to use Lua FFI using LuaJIT to append some text to a file, but I am not very knowledgable of C, so I have some trouble. This is the code:

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()

But I am getting the following error:

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

Solution

  • I have solved this issue with the following code:

    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)