On this page
  1. fgets
  2. Include
  3. Signature & Overview
  4. Notes & Pitfalls
  5. Example

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

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