Assigning an array to a FILE structure

Chris Torek chris at mimsy.umd.edu
Thu Oct 11 13:25:59 AEST 1990


In article <1389 at ashton.UUCP> tomr at ashtate (Tom Rombouts) writes:
>Is it possible using the ANSI stream I/O functions to assign an
>array to a FILE structure so that fgetc() etc. will work on it?

No, not in ANSI C.  On some systems you can open arbitrary functions,
however, and you could thus write your own `read' function that returns
more of the string.

The nice thing about opening `functions' for I/O is that the functions
themselves can open other streams.  For instance:

	struct lzwdata {
		FILE	*l_input;	/* compressed input stream */
		... more stuff needed to implement LZW ...
	};

	/* Refill the given buffer by doing LZW decompression. */
	size_t lzwread(void *cookie, char *buf, size_t n) {
		struct lzwdata *l = cookie;

		... loop reading bytes from l_input ...
		return (count);
	}

	struct ar_data {
		FILE	*ar_input;	/* input data stream */
		long	ar_bytesleft;	/* bytes left in current input */
		... more stuff needed to handle several `files' per file ...
	};
	/* Refill the given archive input stream */
	size_t ar_read(void *cookie, char *buf, size_t n) {
		struct ar_data *ar = cookie;
		size_t ret;

		if (ar->ar_bytesleft == 0)
			return (0);	/* EOF */
		if (ar->ar_bytesleft < n)
			n = cookie->ar_bytesleft;
		ret = fread(buf, 1, n, ar);
		ar->ar_bytesleft -= ret;
		return (ret);
	}

Now if you open an archive and then wrap the lzw decompresser around
it, you get a stream that reads the next compressed subfile from the
archive, while if you open the lzw decompresser and wrap the archive
reader around it, you get a stream that reads the next subfile from
the compressed archive.

Programmers in other languages will recognize this as equivalent to
coroutines.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 405 2750)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list