Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

fgets — C23 stream function

`fgets(s, n, stream)` from `<stdio.h>` reads at most `n - 1` characters into array `s`, stopping after a newline has been read or at end of file. A read newline remains in the array, and the function appends `\0` after the characters obtained.

Version: C23

Syntax

char *fgets(char * restrict s, int n, FILE * restrict stream);

fgets(s, n, stream) from <stdio.h> reads at most n - 1 characters into array s, stopping after a newline has been read or at end of file. A read newline remains in the array, and the function appends \0 after the characters obtained.

The example writes red\nblue to a tmpfile() and calls fgets twice. Output 4 1 blue shows that the first buffer has four characters and includes \n, while the second call reads the final line without a terminating newline.

The result is s on success or null on a read error or when EOF occurs before any character is read; distinguish those cases with feof and ferror. Pass a positive n no greater than the actual capacity or int range. A long line can require multiple calls, and an embedded \0 byte means strlen alone does not describe every character read.

Examples

#include <stdio.h>
#include <string.h>

int main(void) {
    FILE *stream = tmpfile();
    if (stream == NULL) return 1;
    if (fputs("red\nblue", stream) == EOF) { fclose(stream); return 1; }
    rewind(stream);
    char first[8];
    char second[8];
    if (fgets(first, sizeof first, stream) == NULL || fgets(second, sizeof second, stream) == NULL) {
        fclose(stream);
        return 1;
    }
    printf("%zu %d %s\n", strlen(first), strchr(first, '\n') != NULL, second);
    return fclose(stream) == 0 ? 0 : 1;
}

Result

4 1 blue

The example writes `red\nblue` to a `tmpfile()` and calls `fgets` twice. Output `4 1 blue` shows that the first buffer has four characters and includes `\n`, while the second call reads the final line without a terminating newline.

Sources