The C library getc(FILE *stream) function gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream. It is essential for handling file input operations at the character level.
SyntaxFollowing is the C library syntax of the getc() function −
int getc(FILE *stream);Parameters
This function accepts only a single parameters −
On success, the function returns the next character from the specified stream as an unsigned char cast to an int and on failure, If an error occurs or the end of the file is reached, getc returns EOF (which is a constant defined in <stdio.h>.
Example 1: Reading Characters from a FileThis example shows how to read characters from a file using getc and print them to the standard output.
Below is the illustration of C library getc() function.
#include <stdio.h> int main() { FILE *file = fopen("example1.txt", "r"); if (file == NULL) { perror("Error opening file"); return 1; } int ch; while ((ch = getc(file)) != EOF) { putchar(ch); } fclose(file); return 0; }Output
The above code reds the content from the example1.txt file and then produces following result−
Hello, World!Example 2: Reading Until a Specific Character
This example reads characters from the file until it encounters the character !, demonstrating conditional reading with getc.
#include <stdio.h> int main() { FILE *file = fopen("example3.txt", "r"); if (file == NULL) { perror("Error opening file"); return 1; } int ch; while ((ch = getc(file)) != EOF && ch != '!') { putchar(ch); } fclose(file); return 0; }Output
The above code produces following result assuming example3.txt contains the text:"Stop reading here! Continue..."−
Stop reading here
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4