fgetc() in C - Source Code Example

In this source code example, we will see how to use the fgetc() function in C programming with an example.

fgetc() Function Overview

The fgetc() function in C lets you read a character from a file. Think of it as peeking into a book and reading just one letter.

Source Code Example

#include <stdio.h>

int main() {
    FILE *filePtr;
    char ch;

    // Making a sample file first
    filePtr = fopen("sample.txt", "w");
    if (!filePtr) {
        printf("Error making the file.\n");
        return 1;
    }
    fprintf(filePtr, "Hello, Ram! A test text for fgetc.\nGood day!");
    fclose(filePtr);

    // Reading the file with fgetc
    filePtr = fopen("sample.txt", "r");
    if (!filePtr) {
        printf("Error opening the file.\n");
        return 1;
    }

    printf("File says:\n");
    while ((ch = fgetc(filePtr)) != EOF) {
        putchar(ch);
    }

    // Always shut the file when done
    fclose(filePtr);
    return 0;
}

Output

File says:
Hello, Ram! A test text for fgetc.
Good day!

Explanation

1. We first set up a sample file named "sample.txt" and pop in some text.

2. We then open this file in reading mode.

3. Using fgetc(), we grab one letter from our file each time.

4. putchar(ch) then shows the letter we just read.

5. We do this until we've checked out every letter in the file.

6. Finally, we close our file.

It's a simple and easy way to read a file letter by letter.


Comments