CKTIS / C
fgetc — C23 stream function
`fgetc(stream)` from `<stdio.h>` reads the next character from an input stream, advances its position, and returns the byte interpreted as `unsigned char` and then converted to `int`. At end of file or on failure it returns `EOF` and sets the corresponding stream indicator.
Version: C23
Syntax
int fgetc(FILE *stream);fgetc(stream) from <stdio.h> reads the next character from an input stream, advances its position, and returns the byte interpreted as unsigned char and then converted to int. At end of file or on failure it returns EOF and sets the corresponding stream indicator.
The example writes A to a tmpfile(), rewinds it, and calls fgetc twice. Output 1 1 1 0 confirms the first character, EOF on the second attempt, a set end-of-file indicator, and no error indicator.
Always store the result in int; narrowing it to char first can confuse a valid byte with EOF, especially when plain char is signed. After an EOF result, use feof and ferror to distinguish the cause. Text mode may translate character representations, and ungetc can push a character back but is not arbitrary byte seeking.
Examples
#include <stdio.h>
int main(void) {
FILE *stream = tmpfile();
if (stream == NULL) return 1;
if (fputc('A', stream) == EOF) { fclose(stream); return 1; }
rewind(stream);
int first = fgetc(stream);
int second = fgetc(stream);
printf("%d %d %d %d\n", first == 'A', second == EOF, feof(stream) != 0, ferror(stream) != 0);
return fclose(stream) == 0 ? 0 : 1;
}
Result
1 1 1 0
The example writes `A` to a `tmpfile()`, rewinds it, and calls `fgetc` twice. Output `1 1 1 0` confirms the first character, `EOF` on the second attempt, a set end-of-file indicator, and no error indicator.