Home

fgets

fgets is a standard C library function used to read a string from a file stream. It is declared in the header stdio.h and operates on buffers provided by the caller.

The function signature is: char *fgets(char *restrict s, int n, FILE *restrict stream); It reads up to

A key aspect of fgets is that it ensures the buffer is null-terminated, provided that n is

Buffer size and safety: the caller must supply a buffer large enough for n characters, as fgets

Related considerations: fgets is buffered by the C standard I/O library and can be used with any

n-1
characters
from
the
given
stream
and
stores
them
into
the
buffer
pointed
to
by
s,
terminating
the
string
with
a
null
character.
The
read
stops
when
a
newline
is
encountered
or
when
end-of-file
is
reached,
whichever
comes
first.
If
a
newline
is
read,
it
is
included
in
the
resulting
string.
greater
than
zero
and
the
call
does
not
fail
before
any
characters
are
stored.
If
the
end-of-file
is
reached
before
any
characters
are
read,
the
function
returns
NULL.
If
characters
have
been
read,
the
buffer
is
terminated
and
the
function
returns
s
even
if
end-of-file
occurs
without
a
trailing
newline.
In
case
of
an
input
error,
fgets
returns
NULL.
will
read
at
most
n-1
characters
plus
the
terminating
null
byte.
If
n
<=
0,
the
behavior
is
unreliable
according
to
the
standard,
so
such
usage
should
be
avoided.
The
function
does
not
remove
or
trim
newlines
beyond
including
one
in
the
buffer
if
it
is
read.
FILE*
stream,
including
stdin
and
files
opened
via
fopen.
It
is
generally
preferred
over
gets,
which
has
been
removed
due
to
safety
concerns.
To
detect
end-of-file
or
errors,
functions
like
feof
and
ferror
may
be
used
in
conjunction
with
fgets.