ptg10805159
Appendix C Chapter 5 Solutions 913
5.3 The function call
printf("");
returns 0, since no characters areoutput.
5.4 This is a common error.The return value fromgetcandgetcharis anint,not
achar. EOFis often defined to be−1, so if the system uses signed characters, the
code normally works. But if the system uses unsigned characters, after theEOF
returned bygetcharis stored as an unsigned character,the character’s value no
longer equals−1, so the loop never terminates. The four platforms described in
this book all use signed characters, so the example code works on these platforms.
5.5 Callfsyncafter each call tofflush.The argument tofsyncis obtained with
thefilenofunction. Callingfsyncwithout callingfflushmight do nothing if
all the data werestill in memory buffers.
5.6 Standardinput and standardoutput areboth line buffered when a program is run
interactively.Whenfgetsis called, standardoutput is flushed automatically.
5.7 An implementation offmemopenfor BSD-based systems is shown in FigureC.4.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
/*
*Our internal structure tracking a memory stream
*/
struct memstream
{
char *buf; /* in-memory buffer */
size_t rsize; /* real size of buffer */
size_t vsize; /* virtual size of buffer */
size_t curpos; /* current position in buffer */
int flags; /* see below */
};
/* flags */
#define MS_READ 0x01 /* open for reading */
#define MS_WRITE 0x02 /* open for writing */
#define MS_APPEND 0x04 /* append to stream */
#define MS_TRUNCATE 0x08 /* truncate the stream on open */
#define MS_MYBUF 0x10 /* free buffer on close */
#ifndef MIN
#define MIN(a, b) ((a) < (b)? (a) : (b))
#endif
static int mstream_read(void *, char *, int);
static int mstream_write(void *, const char *, int);
static fpos_t mstream_seek(void *, fpos_t, int);
static int mstream_close(void *);