Block 2 · Unit 8File Handling13 min · Section 3 of 8
8.3Character Input and Output
Covers IGNOU MCS-201 §8.3, 8.3.1
The simplest way to process a file is one character at a time. This section introduces the character functions, explains the special value EOF, and shows the correct loop for reading to the end of a file.
The functions
Function
Prototype
Returns
fgetc
int fgetc(FILE *fp);
The next character as an unsigned char converted to int, or EOF at end of file or on error
getc
int getc(FILE *fp);
Same as fgetc
fputc
int fputc(int ch, FILE *fp);
The character written, or EOF on error
putc
int putc(int ch, FILE *fp);
Same as fputc
getc and putc behave exactly like fgetc and fputc; the only difference is that the library is allowed to implement getc and putc as macros, which can be slightly faster.
What EOF is
EOF is not a character stored in the file. Modern operating systems record the length of each file, and the library returns EOF when you try to read past that length.
Because EOF must be different from every possible character, the functions return int, not char. Always store their result in an int variable.
Reading to the end correctly
feof(fp) returns a non-zero value (true) after a read has hit the end of the file, and 0 otherwise. ferror(fp) returns non-zero if an error occurred. They are useful after a loop ends, to find out why it ended.
Counting characters, words and lines
One of the unit’s objectives is to count the words in a file. A word starts whenever a non-space character follows a space (or the start of the file).
Key takeaways
getc/fgetc read one character; putc/fputc write one.
They return int so that EOF (a negative value) can be told apart from every character.
Test the read result for EOF; use feof and ferror only after the loop.
Files contain no end-of-file marker.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a loop that displays a text file on the screen character by character, and say what is printed if the loop is written with feof instead.
Show worked answer
int ch; while ((ch = getc(fp)) != EOF) putchar(ch);. Each character is read and printed, and the loop ends as soon as getc reports the end. If the loop is written as while (!feof(fp)) { ch = getc(fp); putchar(ch); }, the final failed read still runs the body, so putchar(EOF) prints one extra garbage character (byte 255) after the file’s contents.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/file-handling/character-input-and-output/ to read this page.