Giulio Paci
Giulio Paci

Reputation: 303

Is it possible to use functions that acts on FILE* on custom structures?

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?

Upvotes: 2

Views: 427

Answers (1)

Geoff Reedy
Geoff Reedy

Reputation: 36011

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.

Upvotes: 5

Related Questions