Fgetc

From aldeid
Jump to navigation Jump to search

Syntax

int fgetc ( 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).

fgetc and getc are equivalent, except that getc may be implemented as a macro in some libraries.

Parameters

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

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

Source Run
#include <stdio.h>
#include <ctype.h>

int isVowel(char c);

int main(int argc, char *argv[])
{

  FILE *pFile = NULL;
  int c = 0;
  int countVowels = 0;

  pFile = fopen("pets", "r");

  if (pFile==NULL) perror("Error opening file\n");
  else {
    do {
      c = fgetc(pFile);
      if(isVowel(c)) countVowels++;
    } while (c != EOF);
    printf("The file contains %d vowels\n", countVowels);
    fclose(pFile);
  }

  return 0;
}

int isVowel(char c)
{
  c = tolower(c);
  if (c=='a' || c== 'e' || c=='i' || c=='o' || c=='u' || c=='y')
    return 1;
  else
    return 0;
}
$ cat pets
You have 3 pets and prefer cats.
$ ./code 
The file contains 10 vowels