Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary compatibility of FILE*

I am designing C library which does some mathematical calculations. I need to specify serialization interface to be able to save and then load some data. The question is, is it correct (from binary compatibility point of view) to use FILE* pointer in the public API of library?

Target platfoms are:

  • Linux x86, x86_64 with gcc >= 3.4.6
  • Windows x86, x86_64 >= WinXP with VS >= 2008sp1

I need to be as much binary compatible as it possible, so at the moment my variant is the following:

void SMModuleSave(SMModule* module, FILE* dest);
SMModule* SMModuleLoad(FILE* src);

So I am curious if it is correct to use FILE* or better switch to wchar*/char* ?

like image 559
prokher Avatar asked May 31 '26 22:05

prokher


2 Answers

I don't agree with ThiefMaster: there's no benefit in going native (ie using file descriptors of type int on linux and handles of type void * on windows) when there's an equivalent portable solution.

I'd probably go with FILE * instead of opening the files by name from within the library: It might be more of a hassle for library users, but it's also more flexible as most libc implementations provide various ways for file opening (fopen(), _wfopen(), _fdopen(), fdopen(), fmemopen(),...) and you don't have to maintain seperate wide-char APIs yourself.

like image 197
Christoph Avatar answered Jun 03 '26 13:06

Christoph


I'd use neither but let the user pass a file descriptor as an int.

Then you can fdopen() it in your code to get a FILE*.

However, when using windows it might not be the best solution even though it does have some helper functions to get a numeric file descriptor.


However, passing a FILE* or a const char* should be fine, too. I'd prefer passing a filename as it's less code to write if a library takes care of opening/closing a file.

like image 27
ThiefMaster Avatar answered Jun 03 '26 12:06

ThiefMaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!