Monday, February 20, 2012

C Language - getc() : get character from stream

getc

function
<cstdio>
int getc ( FILE * stream );
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 by one character to point to the next character.
getc is equivalent to fgetc and also expects a stream as parameter, but getc may be implemented as a macro, so the argument passed to it should not be an expression with potential side effects.
See getchar for a similar function without stream parameter.

Parameters

stream
pointer to a FILE object that identifies the stream on which the operation is to be performed.

Return Value

The character read is returned as an int value.
If the End-of-File is reached or a reading error happens, the function returns EOF and the corresponding error or eof indicator is set. You can use either ferror or feof to determine whether an error happened or the End-Of-File was reached.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* getc example: money counter */
#include <stdio.h>
int main ()
{
  FILE * pFile;
  int c;
  int n = 0;
  pFile=fopen ("myfile.txt","r");
  if (pFile==NULL) perror ("Error opening file");
  else
  {
    do {
      c = getc (pFile);
      if (c == '$') n++;
    } while (c != EOF);
    fclose (pFile);
    printf ("File contains %d$.\n",n);
  }
  return 0;
}


This program reads an existing file called myfile.txt character by character and uses the n variable to count how many dollar characters ($) does the file contain.

See also

No comments:

Post a Comment