Standard Library Functions in C

adplus-dvertising
fgetc() Function
Previous Home Next

Description

The C library function, The fgetc( ) function returns the next character from the input stream from the current position and increments the file position indicator. The character is read as an unsigned char that is converted to an integer.

Declaration

Following is the declaration for fgetc() function.

int fgetc(FILE *stream)

Parameters

stream - Pointer to a FILE object that identifies an input stream.

Return Value

The fgetc returns the next character on the named input stream. If an error occurs, the fgetc function will set the stream's error indicator and return EOF. If the fgetc function encounters the end of stream, it will set the stream's end-of-file indicator and return EOF.

Example

#include <stdio.h>

int main(void)
{
    FILE *fp;
    int c;

    fp = fopen("datafile.txt", "r"); // error check this!

    // this while-statement assigns into c, and then checks against EOF:

    while((c = fgetc(fp)) != EOF) {
        if (c == 'b') {
            putchar(c);
        }
    }

    fclose(fp);

    return 0;
}

Output

// read all characters from a file, outputting only the letter 'b's
// it finds in the file
Previous Home Next