fgetc() function in C++

In this guide, you will learn what is fgetc() function is in C++ programming and how to use it with an example.

1. fgetc() Function Overview

The fgetc() function, part of the <cstdio> library in C++, is used to retrieve a single character from a given file stream. The function advances the position indicator of the stream and returns the character currently pointed by it as an int.

Signature:

int fgetc(FILE* stream);

Parameters:

- stream: Pointer to the FILE object that identifies the input file stream.

2. Source Code Example

#include <iostream>
#include <cstdio>

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

    // Open the file in read mode
    fp = fopen("sample.txt", "r");
    if(fp == NULL) {
        std::cerr << "Error opening the file." << std::endl;
        return 1;
    }

    std::cout << "Contents of the file:" << std::endl;

    while((ch = fgetc(fp)) != EOF) {
        std::cout << ch;
    }

    // Close the file
    fclose(fp);

    return 0;
}

Output:

(Considering "sample.txt" contains the text "Hello, World!")
Hello, World!

3. Explanation

1. We use a FILE pointer named fp to handle our file operations and a character variable ch to store individual characters read from the file.

2. The file "sample.txt" is opened in read mode using the fopen() function.

3. Using a while loop, we continuously retrieve characters from the file using fgetc() and print them until we reach the end of the file (EOF).

4. Finally, we close the file using fclose().

Note: Always ensure to check if the file was opened successfully before attempting to read or perform other operations. It's also essential to close the file after use to free up system resources.


Comments