C Library - getc() function



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.

Syntax

Following is the C library syntax of the getc() function −

int getc(FILE *stream);

Parameters

This function accepts only a single parameters −

  • FILE *stream: A pointer to a FILE object that specifies an input stream. This FILE object is typically obtained by using the fopen function.

Return Value

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 File

This 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
Advertisements