Crystal C bindings: using fopen

205 views Asked by At

I need to use fopen for a library. Is this the correct approach? Is fopen already defined somewhere? (it would be useful in LibC IMO)

@[Link("c")]
lib LibStd
  type File = Void*
  fun fopen( LibC::Char*, LibC::Char* ): File
  fun fclose( File )
end

It works fine, I would like to know the best way to define it.

2

There are 2 answers

0
Mat On BEST ANSWER

Just a minor improvement that could be useful (this is the current solution that I'm using in my bindings):

@[Link("c")]
lib LibStd
  type File = Void
  fun fopen( filename : LibC::Char*, mode : LibC::Char* ): File*
  fun fclose( stream : File* )
end
4
Julien Portalier On

Dont bother with C. Just use Crystal:

File.open(path) { |file| ... }

If you ever need to access the file descriptor, you may call file.fd.