2 * I/O functions for judges
4 * (c) 2007 Martin Mares <mj@ucw.cz>
16 struct stream *sopen_fd(char *name, int fd)
18 struct stream *s = xmalloc(sizeof(*s) + BUFSIZE + strlen(name) + 1);
20 s->pos = s->stop = s->buf;
21 s->end = s->buf + BUFSIZE;
23 strcpy(s->name, name);
27 struct stream *sopen_read(char *name)
29 int fd = open(name, O_RDONLY);
31 die("Unable to open %s for reading: %m", name);
32 return sopen_fd(name, fd);
35 struct stream *sopen_write(char *name)
37 int fd = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
39 die("Unable to open %s for writing: %m", name);
40 return sopen_fd(name, fd);
43 void sflush(struct stream *s)
48 int len = s->pos - s->buf;
51 int c = write(s->fd, p, len);
53 die("Error writing %s: %m", s->name);
58 s->pos = s->stop = s->buf;
61 void sclose(struct stream *s)
68 static int srefill(struct stream *s)
70 int len = read(s->fd, s->buf, BUFSIZE);
72 die("Error reading %s: %m", s->name);
74 s->stop = s->buf + len;
78 int sgetc_slow(struct stream *s)
80 return (srefill(s) ? *s->pos++ : -1);
83 int speekc_slow(struct stream *s)
85 return (srefill(s) ? *s->pos : -1);