| << Prev | Beej's Guide to C | Next >> |
Get a single character from the console or from a file.
#include <stdio.h> int getc(FILE *stream); int fgetc(FILE *stream); int getchar(void);
All of these functions in one way or another, read a single character
from the console or from a
getc() returns a character from the specified
fgetc() returns a character from the specified
Yes, I cheated and used cut-n-paste to do that last paragraph.
getchar() returns a character from stdin. In fact, it's the same as calling getc(stdin).
All three functions return the
If end-of-file or an error is encountered, all three functions return EOF.
// read all characters from a file, outputting only the letter 'b's
// it finds in the file
#include <stdio.h>
int main(void)
{
FILE *fp;
int c;
fp = fopen("datafile.txt", "r"); // error check this!
// this while-statement assigns into c, and then checks against EOF:
while((c = fgetc(fp)) != EOF) {
if (c == 'b') {
putchar(c);
}
}
fclose(fp);
return 0;
}
| << Prev | Beej's Guide to C | Next >> |