Getc

From aldeid
Jump to navigation Jump to search

Syntax

int getc ( FILE * stream );

Description

Get character from stream

Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced to the next character.

If the stream is at the end-of-file when called, the function returns EOF and sets the end-of-file indicator for the stream (feof).

If a read error occurs, the function returns EOF and sets the error indicator for the stream (ferror).

getc and fgetc are equivalent, except that getc may be implemented as a macro in some libraries. See getchar for a similar function that reads directly from stdin.

Parameters

stream
Pointer to a FILE object that identifies an input stream.
Because some libraries may implement this function as a macro, and this may evaluate the stream expression more than once, this should be an expression without side effects.

Return Value

On success, the character read is returned (promoted to an int value).

The return type is int to accommodate for the special value EOF, which indicates failure:

If the position indicator was at the end-of-file, the function returns EOF and sets the eof indicator (feof) of stream.

If some other reading error happens, the function also returns EOF, but sets its error indicator (ferror) instead.

Example

Let's consider the following code:

#include <stdio.h>

int main(int argc, char *argv[])
{
  char c = 0;

  printf("Give me a letter: ");
  c = getchar();
  printf("You gave me %c\n", c);

  printf("Give me another letter: ");
  c = getchar();
  printf("You gave me %c\n", c);

  return 0;
}

When run, the program is only asking for the 1st letter, as shown below:

$ ./code 
Give me a letter: a
You gave me a
Give me another letter: You gave me 

The reason is that you pressed the ENTER key after the 1st letter, which was still in the buffer. When the program met the second getchar, it already had ENTER in its buffer. A solution is to purge the buffer. Below is a modified version of the program:

#include <stdio.h>

char getChar();

int main(int argc, char *argv[])
{
  char c = 0;

  printf("Give me a letter: ");
  c = getChar();
  printf("You gave me %c\n", c);

  printf("Give me another letter: ");
  c = getChar();
  printf("You gave me %c\n", c);

  return 0;
}

char getChar()
{
  char c = 0;
  // Save 1st key
  c = getchar();
  // Purge all other keys (incl. ENTER)
  while(getchar()!='\n');
  return c;
}

This time, the buffer is purged each time a letter is provided:

$ ./code
Give me a letter: a
You gave me a
Give me another letter: e
You gave me e