On this page
fgets
Prev: vsnprintf | Up: stdio.h | Next: fputs
Rel: stdio.h, stdio.h & File I/O Guide
Ref: cppreference — fgets
Tags: #public #prog #c #stdlib #stdio #tier/core
Include
#include <stdio.h>
Signature & Overview
char *fgets(char *restrict buf, int count, FILE *restrict stream);
Reads at most count - 1 characters up to and including '\n' into buf, always NUL-terminating.
Notes & Pitfalls
- Safe replacement for removed
gets(): Always NUL-terminates and retains the trailing'\n'if it fit—strip it withbuf[strcspn(buf, "\n")] = '\0'.
Example
#include <assert.h>
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *f = tmpfile();
fputs("hello\n", f);
rewind(f);
char buf[32];
assert(fgets(buf, sizeof(buf), f) != NULL);
buf[strcspn(buf, "\n")] = '\0';
assert(strcmp(buf, "hello") == 0);
fclose(f);
}
Linked from
Related notes
- tuts/c/stdlib/stdio/fputs Linked here; links to this page; shared tags: #c, #prog, #stdio, #stdlib, #tier
- tuts/c/stdlib/stdio/vsnprintf Linked here; links to this page; shared tags: #c, #prog, #stdio, #stdlib, #tier
- tuts/c/stdlib/stdio Linked here; links to this page; shared tags: #c, #prog, #stdio, #stdlib
- tuts/c/stdlib/stdio/gets links to this page; shared tags: #c, #prog, #stdio, #stdlib, #tier
- tuts/c/stdlib/stdio/scanf links to this page; shared tags: #c, #prog, #stdio, #stdlib, #tier
- tuts/c/stdlib/stdio_and_file_io Linked here; shared tags: #c, #prog, #stdlib
- tuts/c/stdlib/stdio/fclose shared tags: #c, #prog, #stdio, #stdlib, #tier
- tuts/c/stdlib/stdio/feof shared tags: #c, #prog, #stdio, #stdlib, #tier
- tuts/c/stdlib/stdio/ferror shared tags: #c, #prog, #stdio, #stdlib, #tier
- tuts/c/stdlib/stdio/fflush shared tags: #c, #prog, #stdio, #stdlib, #tier