Portable fopencookie()

This is the code for a very limited implementation of fopencookie() for projects that need it to function in environments where the standard C runtime library (often known as a "libc") does not implement fopencookie() and there are no alternatives available.

This is explicitly designed as a "copylib", which means that you put a copy of this code into your project in order to use it. Due to this particular nature, it is licensed under 3-clause BSD license for broad applicability.


  • No seeking support
  • No r+/w+ support
  • All shared data access must be synchronized (as the accessor runs in another thread now)
  • Callbacks are called asynchronously in another thread so it observably behaves differently than the glibc fopencookie() implementation

How to use

As mentioned earlier, this is a "copylib" and should be copied into your project for use. Additionally, you should check using your build system to see if fopencookie(), funopen(), or any similar alternative is available for your code to use, as you'll certainly want to use those if they are available. A sample set of steps for checking for these functions and conditionally using this code using CMake is included in the project.


I did not write this. In fact, the credit to this code belongs solely to zhasha and nsz in #musl on Freenode IRC. They graciously released the rights to the code in its entirety for me to use, so I put it under the 3-clause BSD license and set up this project for others to be able to use and improve it.

Why it exists

This code was originally written to allow libsolv to function on musl libc. Because the code would likely be quite useful for others who may want to use this function in a similarly constrained environment (such as Bionic libc), I set up this project to host it and allow others to improve it.


Code contributions

Improvements to the code are highly welcome in the form of pull requests.

Non-code contributions

If you wish to show your appreciation for this code with money, please consider becoming a patron of musl libc on Patreon. This code would not exist if it weren't for the kind members of the musl libc community, and they are doing great work to make an excellent libc that is generally useful in a wide range of environments and well-designed.