Misplaced Pages

Getc

Article snapshot taken from[REDACTED] with creative commons attribution-sharealike license. Give it a read and then ask your questions in the chat. We can research this topic together.

This is an old revision of this page, as edited by Bearcat (talk | contribs) at 08:00, 22 October 2011 (External links: categorization/tagging using AWB). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Revision as of 08:00, 22 October 2011 by Bearcat (talk | contribs) (External links: categorization/tagging using AWB)(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
It has been suggested that this article be merged into C_file_input/output. (Discuss) Proposed since October 2011.

getc is one of the character input function. getc reads next character from file and it needs file pointer to tell it which file. It is simplest function to read the file.

Like getchar, getc() may be implemented macro instead of function. getc is equivalent to fgetc. getc returns the next character from the stream referred to by fp; it returns EOF for End Of File or error.

Syntax

int getc( FILE * stream);

Here, parameter stream is the pointer to a FILE object which identify the stream on which the operation is to be performed.

Example

/*getc example*/

#include <stdio.h>
int main()
{
FILE *fp;
int c;
int n = 0;
fp = fopen("myfile.txt", "r");
  if(fp == NULL)
     perror ("Error opening file");
  else
  {
     do  {
         c = getc(fp);
         if(c == '#')
         n++;
         }
     while(c != EOF);
  fclose(fp);
  printf ("File contains %d#.\n",n);
  }
 return 0;
 }

Above program read the file called myfile.txt character by character and uses n variable to count '#' character contained in file.

Return Value

Character read is returned as an int value.

If the End-of-File is reached or error in reading occurs, function returns EOF and corresponding error indicator. We can use either ferror or feof to determine whether an error happened or EOF reached.

See also

fgetc

ungetc

getchar

Reference

External links

This redirect has not been added to any content categories. Please help out by adding categories to it so that it can be listed with similar redirects. (October 2011)
Categories:
Getc Add topic