| Types and objects | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Defined in header <stdio.h> | ||
int fgetc(FILE* stream); | (1) | |
int getc(FILE* stream); | (2) | |
fgetc, except that ifgetc is implemented as a macro, it may evaluate stream more than once, so the corresponding argument should never be an expression with side effects.Contents |
| stream | - | to read the character from |
On success, returns the obtained character as anunsignedchar converted to anint.On failure, returnsEOF.
If the failure has been caused by end-of-file condition, additionally sets theeof indicator (seefeof()) onstream. If the failure has been caused by some other error, sets theerror indicator (seeferror()) onstream.
#include <stdio.h>#include <stdlib.h> int main(void){constchar* fname="/tmp/unique_name.txt";// or tmpnam(NULL);int is_ok=EXIT_FAILURE; FILE* fp=fopen(fname,"w+");if(!fp){perror("File opening failed");return is_ok;}fputs("Hello, world!\n", fp);rewind(fp); int c;// note: int, not char, required to handle EOFwhile((c= fgetc(fp))!=EOF)// standard C I/O file reading loopputchar(c); if(ferror(fp))puts("I/O error when reading");elseif(feof(fp)){puts("End of file is reached successfully"); is_ok=EXIT_SUCCESS;} fclose(fp);remove(fname);return is_ok;}
Possible output:
Hello, world!End of file is reached successfully
| reads a character fromstdin (function)[edit] | |
(removed in C11)(C11) | reads a character string fromstdin (function)[edit] |
| writes a character to a file stream (function)[edit] | |
| puts a character back into a file stream (function)[edit] | |
C++ documentation forfgetc,getc | |