2 * I/O functions for judges
4 * (c) 2007 Martin Mares <mj@ucw.cz>
16 struct stream *sopen_fd(char *name, int fd)
18 char *slash = strrchr(name, '/');
19 char *basename = (slash ? slash+1 : name);
20 struct stream *s = xmalloc(sizeof(*s) + BUFSIZE + strlen(basename) + 1);
22 s->pos = s->stop = s->buf;
23 s->end = s->buf + BUFSIZE;
25 strcpy(s->name, basename);
29 struct stream *sopen_read(char *name)
31 int fd = open(name, O_RDONLY);
33 die("Unable to open %s for reading: %m", name);
34 return sopen_fd(name, fd);
37 struct stream *sopen_write(char *name)
39 int fd = open(name, O_WRONLY | O_CREAT | O_TRUNC, 0666);
41 die("Unable to open %s for writing: %m", name);
42 return sopen_fd(name, fd);
45 void sflush(struct stream *s)
50 int len = s->pos - s->buf;
53 int c = write(s->fd, p, len);
55 die("Error writing %s: %m", s->name);
60 s->pos = s->stop = s->buf;
63 void sclose(struct stream *s)
70 static int srefill(struct stream *s)
72 int len = read(s->fd, s->buf, BUFSIZE);
74 die("Error reading %s: %m", s->name);
76 s->stop = s->buf + len;
80 int sgetc_slow(struct stream *s)
82 return (srefill(s) ? *s->pos++ : -1);
85 int speekc_slow(struct stream *s)
87 return (srefill(s) ? *s->pos : -1);