Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!samsung!noose.ecn.purdue.edu!iuvax!purdue!haven!mimsy!chris From: chris@mimsy.umd.edu (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Assigning an array to a FILE structure Keywords: file I/O, streams Message-ID: <26931@mimsy.umd.edu> Date: 11 Oct 90 03:25:59 GMT References: <1389@ashton.UUCP> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 54 In article <1389@ashton.UUCP> tomr@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@cs.umd.edu Path: uunet!mimsy!chris