Trouble using and understanding funopen(3)

Farhan Khan farhan at farhan.codes
Sun Aug 25 22:51:35 UTC 2019


August 22, 2019 4:28 PM, "Conrad Meyer" <cem at freebsd.org> wrote:

> Hi Farhan,
> 
> First, I'd suggest using the more portable fopencookie(3) interface,
> which is similar to funopen(3).
> 
> Second, read functions return 0 to indicate end of file.
> 
> Finally, the file cookie routines are stateful. If you want to create
> a pseudo-FILE that only has 10 bytes in it, you have to track the
> current file offset by creating a cookie. Here is a minimal example
> of using a cookie.
> 
> struct my_file {
> off_t offset;
> };
> 
> my_read(void *v, buf, len)
> {
> struct my_file *f = v;
> size_t rlen;
> 
> /* Indicate EOF for reads past EOF. */
> if (f->offset >= 10)
> return (0);
> 
> rlen = MIN(len, 10 - f->offset);
> memcpy(buf, "AAAAAAAAAA", rlen);
> f->offset += rlen;
> 
> return ((int)rlen);
> }
> 
> main()
> {
> struct my_file *cookie;
> FILE *f;
> char buf[100];
> size_t x;
> 
> cookie = calloc(1, sizeof(*cookie));
> f = fopencookie(cookie, "rb", { .read = my_read, });
> 
> x = fread(buf, 1, sizeof(buf), f);
> ...
> }
> 
> Conrad
> 
> On Thu, Aug 22, 2019 at 9:24 AM Farhan Khan via freebsd-hackers
> <freebsd-hackers at freebsd.org> wrote:
> 

Conrad,

Took me a while to massage that into the format I wanted, but I got it working. Thanks!

To be honest, I had trouble understanding the manual. I was mistakenly under the impression that the readfn function was literally just a pass-through to whatever read mechanism you implement. It also was not obvious how the return value is interpreted. Do you think it might be useful to get an update to the documentation? Or was this me failing to understand the way funopen worked?

Also, Linux's fopencookie(3) has a code sample. That might be good to have as well.

Thanks

---
Farhan Khan
PGP Fingerprint: 1312 89CE 663E 1EB2 179C  1C83 C41D 2281 F8DA C0DE


More information about the freebsd-hackers mailing list