Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 25 Aug 2019 22:50:55 +0000
From:      "Farhan Khan" <farhan@farhan.codes>
To:        cem@freebsd.org
Cc:        freebsd-hackers@freebsd.org
Subject:   Re: Trouble using and understanding funopen(3)
Message-ID:  <0562c72f444c42097b5af75733686ff5@farhan.codes>
In-Reply-To: <CAG6CVpWryJeA5DXZMNZ5cfrfexzEx_ewy9CB5HbFgNtjj=GwPg@mail.gmail.com>
References:  <CAG6CVpWryJeA5DXZMNZ5cfrfexzEx_ewy9CB5HbFgNtjj=GwPg@mail.gmail.com> <519c2fce85fe0db1cd189d2060f09a0f@farhan.codes>

next in thread | previous in thread | raw e-mail | index | archive | help
August 22, 2019 4:28 PM, "Conrad Meyer" <cem@freebsd.org> wrote:=0A=0A> H=
i Farhan,=0A> =0A> First, I'd suggest using the more portable fopencookie=
(3) interface,=0A> which is similar to funopen(3).=0A> =0A> Second, read =
functions return 0 to indicate end of file.=0A> =0A> Finally, the file co=
okie routines are stateful. If you want to create=0A> a pseudo-FILE that =
only has 10 bytes in it, you have to track the=0A> current file offset by=
 creating a cookie. Here is a minimal example=0A> of using a cookie.=0A> =
=0A> struct my_file {=0A> off_t offset;=0A> };=0A> =0A> my_read(void *v, =
buf, len)=0A> {=0A> struct my_file *f =3D v;=0A> size_t rlen;=0A> =0A> /*=
 Indicate EOF for reads past EOF. */=0A> if (f->offset >=3D 10)=0A> retur=
n (0);=0A> =0A> rlen =3D MIN(len, 10 - f->offset);=0A> memcpy(buf, "AAAAA=
AAAAA", rlen);=0A> f->offset +=3D rlen;=0A> =0A> return ((int)rlen);=0A> =
}=0A> =0A> main()=0A> {=0A> struct my_file *cookie;=0A> FILE *f;=0A> char=
 buf[100];=0A> size_t x;=0A> =0A> cookie =3D calloc(1, sizeof(*cookie));=
=0A> f =3D fopencookie(cookie, "rb", { .read =3D my_read, });=0A> =0A> x =
=3D fread(buf, 1, sizeof(buf), f);=0A> ...=0A> }=0A> =0A> Conrad=0A> =0A>=
 On Thu, Aug 22, 2019 at 9:24 AM Farhan Khan via freebsd-hackers=0A> <fre=
ebsd-hackers@freebsd.org> wrote:=0A> =0A=0AConrad,=0A=0ATook me a while t=
o massage that into the format I wanted, but I got it working. Thanks!=0A=
=0ATo 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?=0A=0AAlso, Linux's fopencookie(3) has a code samp=
le. That might be good to have as well.=0A=0AThanks=0A=0A---=0AFarhan Kha=
n=0APGP Fingerprint: 1312 89CE 663E 1EB2 179C  1C83 C41D 2281 F8DA C0DE



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?0562c72f444c42097b5af75733686ff5>