Pointer to the file stream from which a character is to be read The FILE pointer parameter infgetcmust: ● Be valid pointer from previous successful fopen; ● Point to a stream opened in read mode ("r", "r+", "w+", "a+"); ● Not be NULL (undefined behavior); ● Not be invalidated by previous fclose; After successful read: ● Stream position advances by one character; ● Parameter remains valid for next read; After EOF/error: ● Stream position remains unchanged; ● Parameter remains valid but needs error checking;
Read more about parameters of fgetc in parameters section
The fgetcfunction in C language reads the next character from the specified file stream.
fgetc is a fundamental character input function that reads a single character from a stream, making it ideal for character-by-character processing of files. It's distinguished by its behavior of returning an int (not char) to properly handle both regular characters (0-255) and EOF (-1), which helps avoid potential sign extension issues. The function integrates with the stdio.h error handling system - particularly feof and ferror for checking read status, and pairs naturally with ungetc for pushing characters back into the stream. It's often used in scenarios requiring precise character-level control or when parsing formatted text files.
To Summarize the Workflow:
1.
Takes FILE pointer as parameter
2.
Reads single character from input stream
3.
Returns character as unsigned char converted to int (0-255)
4.
Returns EOF (-1) on end-of-file or error
5.
Advances file position indicator on successful read
Read more about return type and value offgetc function in return section.
The fgetcfunction takes 1
parameter:
•
FILE * `stream`: Pointer to the file stream from which a character is to be read The FILE pointer parameter infgetcmust: ● Be valid pointer from previous successful fopen; ● Point to a stream opened in read mode ("r", "r+", "w+", "a+"); ● Not be NULL (undefined behavior); ● Not be invalidated by previous fclose; After successful read: ● Stream position advances by one character; ● Parameter remains valid for next read; After EOF/error: ● Stream position remains unchanged; ● Parameter remains valid but needs error checking;
The fgetc function return value :
On success returns character read converted to unsigned char then to int (0-255); On failure returns EOF (-1) with appropriate indicator set (error or EOF); Important: in both failure cases (EOF or error) fgetc() returns EOF (-1) The only way to distinguish between the two failure types is to check the indicators using feof() and ferror()
Output
This example demonstrates the basic usage of `fgetc`. It reads a file character by character and prints each character to the console.