A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
Parsers constantly face this problem: you read one character too far. You were scanning for a delimiter, you found it, but now that delimiter is consumed and the next stage of parsing needs to see it. ungetc pushes a single character back onto the stream. The next fgetc returns it as if it was never read. The standard guarantees at least one character of pushback. Most implementations give you more, but you should not rely on that.
#include <stdio.h>#include <ctype.h>int main(void) {FILE *fp = fopen("data.csv", "w");fputs("hello,world,foo", fp);fclose(fp);fp = fopen("data.csv", "r");if (fp == NULL) {perror("fopen");return 1;}int ch;printf("Token: ");while ((ch = fgetc(fp)) != EOF) {if (ch == ',') {printf("\nToken: ");} else {putchar(ch);}}printf("\n");fclose(fp);return 0;}
That simple version consumes the comma. Now imagine a parser where the comma carries meaning for the next stage. You read it, recognize it, and push it back so the caller can process it.
#include <stdio.h>int read_until_delimiter(FILE *fp, char delim) {int ch;while ((ch = fgetc(fp)) != EOF) {if (ch == delim) {ungetc(ch, fp);return 1;}putchar(ch);}return 0;}int main(void) {FILE *fp = fopen("data.csv", "r");if (fp == NULL) {perror("fopen");return 1;}printf("First field: ");read_until_delimiter(fp, ',');int delim = fgetc(fp);printf("\nDelimiter found: '%c' (ASCII %d)\n", delim, delim);fclose(fp);return 0;}
The function reads until it finds the comma, pushes it back, and returns. The caller then reads the comma itself. The stream is in a consistent state. No character was lost. This pattern appears in recursive descent parsers, lexical analyzers, and protocol decoders throughout production C code.
ungetc is the parser's undo button. Small, simple, and essential for any code that needs to peek ahead without consuming. Next: fprintf, which is printf pointed at a file instead of stdout, and which has a few behavioral differences worth knowing.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.