fgetc - Linux


Overview

fgetc reads a single character from a stream. It is commonly used for processing text input, parsing configuration files, and other text-based operations.

Syntax

char fgetc(FILE *stream);

Options/Flags

None

Examples

Read a character from standard input:

#include <stdio.h>

int main() {
    char c = fgetc(stdin);
    printf("Entered character: %c\n", c);
    return 0;
}

Read a character from a file:

#include <stdio.h>

int main() {
    FILE *file = fopen("myfile.txt", "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    char c = fgetc(file);
    while (c != EOF) {
        printf("%c", c);
        c = fgetc(file);
    }

    fclose(file);
    return 0;
}

Common Issues

  • Invalid stream: Ensure that the stream parameter points to a valid, open file or standard input stream.
  • End-of-file: fgetc will return EOF when the end of the stream is reached. Handle this condition appropriately to avoid errors.

Integration

fgetc can be used in combination with other commands and tools for advanced tasks, such as:

  • grep: Filter text based on a specific character or pattern.
  • sed: Perform text substitutions using character-based matching.
  • awk: Extract and manipulate data from text files using character-based operations.

Related Commands

  • fscanf: Read formatted input from a stream.
  • getc: Read a single character from a stream as a byte.
  • fputc: Write a single character to a stream.