'custom FILE type in C/C++

Is it possible in C/C++ to create my own custom stream of type FILE (stdio.h) that can be used with fputs() for example ?



Solution 1:[1]

No it isn't. FILE is what is known as an opaque type - it doesn't have anything you can customise.

Solution 2:[2]

If you are compiling with the GNU C library you could use fmemopen(3):

fmemopen, open_memstream, open_wmemstream - open memory as stream

Solution 3:[3]

There is no standard way with the FILE interface. Note that C++ code usually should use IOStream for IO, with the IOStream interface, writing a custom streambuf is the solution to your problem.

If you can drop standard conformance, look at the documentation of your implementation.

  • POSIX has a popen() function which create a FILE* reading from the output or writing to the input of a process;

  • POSIX has a fdopen() which is able to create a FILE* from a file descriptor;

  • At least for the GNU libc used by Linux, there is a possibility of defining custom C stream (see the "Programming your awn custom streams" section in the info documentation).

Solution 4:[4]

It is possible. But you should link your application with your version of fputs(), etc instead of those coming with the standard libraries. Most compilers link to the standard IO libraries by default. You have to figure out how to get around that.

Solution 5:[5]

Everyone here is a tad wrong; (or where in 2009); at least if you count glibc as a psuedo-canoncial standard library.

See GCC's whole section on custom streams:

https://www.gnu.org/software/libc/manual/html_node/Custom-Streams.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Inshallah
Solution 3
Solution 4 Vijay Mathew
Solution 5 Hunter Kohler