2

Very often I see libraries that implements their own stream functionalities, instead of using FILE*. The typical interface will have a close function, similar to fclose(), and several open functions, one of which usually mimics fopen() and one of which usually accepts a few callbacks that should be used to open/close the stream, read to/write from the stream.

As a reference, good examples of what I am talking about are http://www.xmlsoft.org/xmlio.html or https://developer.gnome.org/gio/.

The approach, in general, seems very straightforward to me, however these libraries do not usually implement a replacement for all the functions in the standard library (e.g., fscanf(), fprintf(), ...).

Thus I wonder if an extension mechanism is available for standard library FILE* as well (e.g.: opening by providing callbacks for some low-level required functionalities). I was not able to find any reference about this capability, so I guess it is not part of any standard.

Anyway, here is my question: is this functionality available in the C standard library (any standard is fine, as long as it is portable)? If not is there any easy (i.e., it does not require to re-implement the whole stdio.h functions) option that allows to implement it on top of the standard library?

Giulio Paci
  • 303
  • 1
  • 7
  • 2
    Most likely libraries like that just *wraps* the normal standard I/O functions, i.e. their private structure contains a `FILE *` member that the library uses internally. Either that, or it wraps the native operating systems functions (`open`/`close`/`read`/`write` on POSIX systems, `CreateFile`/`CloseHandle`/`ReadFile`/`WriteFile` on Windows). – Some programmer dude Feb 08 '16 at 15:05
  • Indeed they are wrapping FILE* when accessing files, but I was interested in the extension of what FILE* handles. Essentially I want to express my streams in term of callbacks that can retrieve/write data and still be able to use standard functions on top of this callback. The answer from @Geoff Reedy shows clearly what I am looking for. – Giulio Paci Feb 08 '16 at 17:16
  • Here are two related questions http://stackoverflow.com/questions/7307955/fmemopen-for-mingw http://stackoverflow.com/questions/13217690/is-there-no-fopencookie-or-fmemopen-in-mingw – Giulio Paci Feb 08 '16 at 17:31

1 Answers1

5

It depends on the C library you're using. Glibc, for example, supports custom streams through fopencookie (further documentation here). FreeBSD (and probably other BSDs as well, including OS X) have funopen. It doesn't look like Microsoft's C library supports such a feature.

Geoff Reedy
  • 34,891
  • 3
  • 56
  • 79
  • Hi, thank you for your answer. So apparently there is indeed no standard, but some C standard libraries offer this functionality. The answer is missing the portability requirement, but it already addresses many of the points. – Giulio Paci Feb 08 '16 at 17:07