C programming getc stdio.h


In C programming the <stdio.h> getc function gets the character from the stream.The declaration of the function is given below.

int getc(FILE *stream);

Parameters:
stream -The stream from which a character is to be read.

Return type
int -Rreturns the next character from the input stream pointed to by stream.If the stream is at end of-file, the end-of-file indicator for the stream is set and ‘getc’ returns EOF.If a read error occurs,the error indicator for the stream is set and ‘getc’ returns ‘EOF’.

Note ‘getc’ is same as ‘fgetc’ except ‘getc’ is implemented as macro.

Link : C fgetc stdio.h

A code example is given below.

Code example

FILE *fp=fopen(“text.txt” , “r+”);  //text.txt can be any file

int c ;

while( (c=getc(fp)) !=EOF )
{
printf(“%c” , c);
}

fclose(fp);

The output is the content of the ‘text.txt’ file.





Which should I prefer ‘fgetc’ or ‘getc’

Both the functions ‘fgetc’ and ‘getc’ perform the same operation:to read character from the stream.However, the question is which should I/you prefer.The ‘getc’ is a macro so sometimes it may evaluate it’s argument more than once meaning it may read from the same argument twice and this can lead to reading the same character twice or even more.Due to this reason it is strongly advised to not make the argument an expression with side effect or you can simply opt for ‘fgetc’ over ‘getc’ which is safer.

Code example

FILE *fp[15];

int c , i=0 ;

do( c=getc( fp[i++]) )
{
/*… process the character ‘c’ …*/
}
while(i<15)

fclose(fp);

If the argument is evaluated more than once in the above program some of the stream will not be processed,hence this can lead to an unexpected result.A more secure program is given below.

Code example

FILE *fp[15];

int c , i=0 ;

for(int i=0; i<15 ; i++)
{
c=getc( fp[i]) )

/*… process the character ‘c’ …*/
}

fclose(fp);

Here there is no chance of evaluating the argument twice since ‘for’ statement takes care of incrementing the index value of the stream array.Another solution besides the above program is using the ‘fgetc’ function which is way safer then ‘getc’ function.

P.S. you should prefer ‘fgetc’ over ‘getc’.


Related links

->C getchar stdio.h

->C ungetc stdio.h

->C fopen stdio.h

->C fclose stdio.h