C++ getc()

getc() prototype

int getc(FILE* stream);

The getc() function takes a file stream as its argument and returns the next character from the given stream as a integer type.

Difference between getc() and fgetc()

The getc() and fgetc() functions in C++ are almost similar. However there are some differences between them.

The getc() function can be implemented as a macro whereas fgetc() function can not be used as macro.

Also getc() function is highly optimized and hence calls to fgetc() probably take longer than calls to getc(). So, getc() is preferred in most situations.

It is defined in <cstdio> header file.

getc() Parameters

stream: The file stream to read the character.

getc() Return value

  • On success, the getc() function returns the read character.
  • On failure it returns EOF.
    • If the failure is caused due to end of file, it sets the eof indicator.
    • If the failure is caused by other errors, it sets the error indicator.

Example: How getc() function works

#include <cstdio>

int main()
{
    int c;
    FILE *fp;
    
    fp = fopen("file.txt","r");
    
    if (fp)
    {
        while(feof(fp) == 0)
        {
            c = getc(fp);
            putchar(c);
        }
    }
    else
        perror("File opening failed");
    fclose(fp);
    return 0;
}

When you run the program, a possible output will be:

Hello World!

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges