openat: don’t close (-1)
[gnulib.git] / lib / sf-istream.c
blob1bc4fa15e5ef36a949b6703bb289a112ec3a0995
1 /* A string or file based input stream.
2 Copyright (C) 2024 Free Software Foundation, Inc.
4 This file is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation, either version 3 of the
7 License, or (at your option) any later version.
9 This file is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Written by Bruno Haible <bruno@clisp.org>, 2024. */
19 #include <config.h>
21 /* Specification. */
22 #include "sf-istream.h"
24 #include <stdlib.h>
25 #include <string.h>
27 void
28 sf_istream_init_from_file (sf_istream_t *stream, FILE *fp)
30 stream->fp = fp;
31 stream->input = NULL;
32 stream->input_end = NULL;
35 void
36 sf_istream_init_from_string (sf_istream_t *stream,
37 const char *input)
39 stream->fp = NULL;
40 stream->input = input;
41 stream->input_end = input + strlen (input);
44 void
45 sf_istream_init_from_string_desc (sf_istream_t *stream,
46 string_desc_t input)
48 stream->fp = NULL;
49 stream->input = string_desc_data (input);
50 stream->input_end = stream->input + string_desc_length (input);
53 int
54 sf_getc (sf_istream_t *stream)
56 int c;
58 if (stream->fp != NULL)
59 c = getc (stream->fp);
60 else
62 if (stream->input == stream->input_end)
63 return EOF;
64 c = (unsigned char) *(stream->input++);
67 return c;
70 int
71 sf_ferror (sf_istream_t *stream)
73 return (stream->fp != NULL && ferror (stream->fp));
76 void
77 sf_ungetc (sf_istream_t *stream, int c)
79 if (c != EOF)
81 if (stream->fp != NULL)
82 ungetc (c, stream->fp);
83 else
85 stream->input--;
86 if (!(c == (unsigned char) *stream->input))
87 /* C was incorrect. */
88 abort ();
93 void
94 sf_free (sf_istream_t *stream)