C programming fgetc stdio.h


In C programming the <stdio.h> fgetc function is used to read character from the file at the current position in the specified file and increment the position associated with the stream.The declaration of the function is given below.

int fgetc(FILE *stream);

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

Return type
int -Returns the next character from the input stream pointed to by ‘stream’ as int type.If the stream points to EOF the end-of-file indicator for the stream is set and the function returns EOF.Note EOF corresponds to the integer value 255.

**Note if you convert the returned value to char type you might not be able to distinguished between EOF and ‘\xFF’,both the character has an integer value of 255.

A code example is given below and it reads character from a file (‘text.txt’).Consider that the file ‘text.txt’ has the content “New string 124345 66 255

Code example

FILE *fp = fopen(“text.txt” , “r”);

int c ;

if (fp != NULL)
{
while ((c = fgetc(fp)) != EOF)
{
 printf(“%c” , c);
}
}
else
 fprintf(stderr , “File opening failed”);

fclose( fp );

Output,

New string 124345 66 255

Note although ‘c’ is int type the conversion specifier used when outputting the returned value is ‘%c’:which is meant for char type.This allows printing out the returned value as character not integer.





You can also use ‘fgetc while dealing with binary files.In this case simply change the mode to binary mode ‘rb’ or any other suitable binary mode.A code example is given below and also for this example consider a file name ‘text.bin’ consisting of the string “ÆÆšý„gñþ†ø¾x¾œ¢Žðƒ.k?¡óéØìןþ¾íÝùøa“.

Code example

FILE *fp = fopen(“text.bin” , “rb”);

int c ;

if (fp != NULL)
{
while ((c = fgetc(fp)) != EOF)
{
 printf(“%c” , c);
}
}
else
 fprintf(stderr , “File opening failed”);

fclose( fp );

Output in Code::Blocks,

ÆÆšý„gñþ†ø¾x¾œ¢Žðƒ.k?¡óéØìןþ¾íÝùøa


Related links

->C ungetc stdio.h

->C fopen stdio.h

->C getchar stdio.h

->C fclose stdio.h

->C fprintf stdio.h