These are the notes for C Coding Questions, episode 29, placement practice for people who finished the SyntaxPilot C course. Three file handling questions: counting the lines, words and characters of a file (like the wc command), copying a file, and appending and reading records with fprintf and fscanf.
Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.
Every program was compiled with gcc -Wall -O2 -Wno-unused-result main.c -o main -lm (gcc 13.3, glibc, Linux x86-64), the SyntaxPilot compiler's C command with warnings on, and run in an empty folder, like the online compiler does. That's why every program starts by writing its own test files with a small helper, make_file. Every output below is real; the fixed programs were also run under valgrind: no errors, no leaks.
Real-life pictures
| In real life | In C |
|---|---|
| a teacher counting the words of an essay: two spaces don't make an extra word, a blank page has none | count lines, words, chars: count where words start |
| a photocopy copies every mark on the page, spaces and blank lines too | copy a file: every byte, with fgetc and fputc |
| a shop's register book: today's line is added at the end; tearing out the old pages loses yesterday | append records: mode "a", never "w" |
A quick reminder of the file functions (episode 15 of the C course):
| Function | What it does |
|---|---|
FILE *fp = fopen(name, mode) |
opens a file; returns a FILE pointer (a handle), or NULL if it can't |
| modes | "r" read · "w" write (creates, or empties an existing file) · "a" append (adds at the end) · add b for binary: "rb", "wb" |
fgetc(fp) |
reads one byte and returns it as an int, or EOF at the end |
fputc(c, fp) · fputs(s, fp) · fprintf(fp, ...) |
write a byte · a string · formatted text |
fscanf(fp, ...) |
reads formatted input; returns how many items it filled, or EOF |
feof(fp) |
true only after a read has already failed at the end of the file |
perror(msg) |
prints msg: <reason> to the error stream, e.g. No such file or directory |
fclose(fp) |
flushes and closes the file |
Q1: Count the lines, words and characters of a file
Problem. Print the number of lines, words and characters (bytes) in a file, like wc.
Think out loud.
poem.txtholdsTwinkle twinkle\nlittle star\nhow I wonder(two spaces afterlittle, no newline at the end). Answer: 3 lines, 7 words, 41 characters.- A word is a run of characters between whitespace (spaces, tabs, newlines). Characters = every byte, newlines included. Lines = lines of text, so a last line with no
\nstill counts. (wc -lcounts only\ncharacters, so it prints 2 for this file; it agrees on 7 words and 41 bytes.) - Edge cases: two spaces in a row, a last line with no
\n, an empty file (0, 0, 0), a file that doesn't exist.
The obvious attempt: while (!feof(fp)) and "spaces + 1"
#include <stdio.h>
#include <stdlib.h>
void make_file(const char *name, const char *text) { /* test input */
FILE *fp = fopen(name, "w");
if (fp == NULL) { perror(name); exit(1); }
fputs(text, fp);
fclose(fp);
}
void count(const char *name) {
FILE *fp = fopen(name, "r");
if (fp == NULL) { perror(name); return; }
int lines = 0, words = 0, chars = 0;
char c;
while (!feof(fp)) {
c = fgetc(fp);
chars++;
if (c == '\n') lines++;
if (c == ' ') words++;
}
words++; /* words = spaces + 1 */
printf("%s: %d lines, %d words, %d chars\n", name, lines, words, chars);
fclose(fp);
}
int main() {
make_file("poem.txt", "Twinkle twinkle\nlittle star\nhow I wonder");
make_file("empty.txt", "");
count("poem.txt");
count("empty.txt");
return 0;
}
Real output:
poem.txt: 2 lines, 6 words, 42 chars
empty.txt: 0 lines, 1 words, 1 chars
Why it failed
Three bugs:
- One character too many (42, and 1 for an empty file).
feofturns true only after a read has failed. After the last real character is read,feofis still false, so the loop runs once more;fgetcreturns EOF (a specialintvalue meaning "end of file", -1 on this system) and we count it. - Wrong words (6, and 1 for an empty file). "Spaces + 1" counts the two spaces after
littleas two word breaks, misses the newlines between words, and gives 1 for an empty file. - Wrong lines (2). The last line has no
\n.
And a hidden fourth: char c can't hold every byte and EOF. fgetc returns an int from 0 to 255, or EOF. Stored in a (signed) char, a real byte 0xFF (255) becomes -1 and looks like EOF; with an unsigned char, EOF never matches and the loop never ends.
The fix: int c, read then test, count where words start
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void make_file(const char *name, const char *text) { /* test input */
FILE *fp = fopen(name, "w");
if (fp == NULL) { perror(name); exit(1); }
fputs(text, fp);
fclose(fp);
}
void count(const char *name) {
FILE *fp = fopen(name, "r");
if (fp == NULL) { perror(name); return; }
int lines = 0, words = 0, chars = 0, in_word = 0, last = '\n';
int c; /* int, so it can hold EOF */
while ((c = fgetc(fp)) != EOF) { /* read, THEN test */
chars++;
if (c == '\n') lines++;
if (isspace(c)) in_word = 0;
else if (!in_word) { in_word = 1; words++; } /* a word starts */
last = c;
}
if (last != '\n') lines++; /* last line has no '\n' */
printf("%s: %d lines, %d words, %d chars\n", name, lines, words, chars);
fclose(fp);
}
int main() {
make_file("poem.txt", "Twinkle twinkle\nlittle star\nhow I wonder");
make_file("empty.txt", "");
make_file("spaces.txt", " \n hi there \n");
count("poem.txt");
count("empty.txt");
count("spaces.txt");
count("missing.txt");
return 0;
}
Real output (the error stream is shown first by the terminal here; on the SyntaxPilot compiler it appears in its own box):
missing.txt: No such file or directory
poem.txt: 3 lines, 7 words, 41 chars
empty.txt: 0 lines, 0 words, 0 chars
spaces.txt: 2 lines, 2 words, 19 chars
wc on the same three files: 2 7 41 poem.txt, 0 0 0 empty.txt, 2 2 19 spaces.txt (2 lines for poem.txt, because wc counts \n characters).
while ((c = fgetc(fp)) != EOF): read first, then test. The assignment happens inside the condition, and the brackets aroundc = fgetc(fp)are needed because!=binds tighter than=.isspace(c)(from<ctype.h>) is true for space, tab, newline and a few others. A non-space character whilein_word == 0is the start of a word.
Complexity. O(n) time for a file of n bytes, each byte read once. O(1) space: a few counters, however large the file.
Q2: Copy a file
Problem. Copy menu.txt to copy.txt so the two have exactly the same bytes.
Think out loud.
menu.txtholdsMasala Dosa 60\nIdli 40\n\nChai 15\n: a double space and a blank line.- A helper
same(a, b)opens both files and compares them byte by byte, so we don't trust our eyes. - Edge cases: the double space, the blank line, an empty file, a source file that doesn't exist.
The obvious attempt: fscanf("%s") and no NULL checks
#include <stdio.h>
#include <stdlib.h>
void make_file(const char *name, const char *text) { /* test input */
FILE *fp = fopen(name, "w");
if (fp == NULL) { perror(name); exit(1); }
fputs(text, fp);
fclose(fp);
}
int same(const char *a, const char *b); /* compare byte by byte */
void copy(const char *src, const char *dst) {
FILE *in = fopen(src, "r");
FILE *out = fopen(dst, "w");
char word[100];
while (fscanf(in, "%99s", word) == 1)
fprintf(out, "%s\n", word);
fclose(in);
fclose(out);
}
int main() {
make_file("menu.txt", "Masala Dosa 60\nIdli 40\n\nChai 15\n");
copy("menu.txt", "copy.txt");
printf("menu.txt -> copy.txt: %s\n", same("menu.txt", "copy.txt") ? "identical" : "DIFFERENT");
fflush(stdout);
copy("nofile.txt", "copy2.txt");
printf("done\n");
return 0;
}
/* ── helper: 1 if the two files have exactly the same bytes ── */
int same(const char *a, const char *b) {
FILE *f = fopen(a, "rb"), *g = fopen(b, "rb");
int ok = (f != NULL && g != NULL), x, y;
while (ok) {
x = fgetc(f); y = fgetc(g);
if (x != y) ok = 0;
if (x == EOF || y == EOF) break;
}
if (f) fclose(f);
if (g) fclose(g);
return ok;
}
Real output:
menu.txt -> copy.txt: DIFFERENT
and then the program crashes: the exit status is 139 (signal 11, Segmentation fault, which the SyntaxPilot compiler shows in red). done is never printed. The fflush(stdout) makes sure the first line is shown before the crash; without it, the line would still be in the output buffer when the program dies.)
What copy.txt holds:
Masala
Dosa
60
Idli
40
Chai
15
Why it failed
%sreads words: it skips spaces, tabs and newlines. So the double space, the blank line and the line structure are lost. A copy must not interpret the file; it just moves bytes.fopen("nofile.txt", "r")returns NULL. Passing NULL tofscanfreads through a NULL pointer: undefined behaviour, here a segmentation fault (the operating system stops a program that touches memory it doesn't own).
The fix: every byte, binary mode, check every fopen
#include <stdio.h>
#include <stdlib.h>
void make_file(const char *name, const char *text) { /* test input */
FILE *fp = fopen(name, "w");
if (fp == NULL) { perror(name); exit(1); }
fputs(text, fp);
fclose(fp);
}
int same(const char *a, const char *b); /* compare byte by byte */
long copy(const char *src, const char *dst) { /* bytes, or -1 */
FILE *in = fopen(src, "rb");
if (in == NULL) { perror(src); return -1; } /* check EVERY fopen */
FILE *out = fopen(dst, "wb");
if (out == NULL) { perror(dst); fclose(in); return -1; }
long n = 0;
int c;
while ((c = fgetc(in)) != EOF) { /* every byte: spaces, '\n', all */
fputc(c, out);
n++;
}
fclose(in);
fclose(out);
return n;
}
int main() {
make_file("menu.txt", "Masala Dosa 60\nIdli 40\n\nChai 15\n");
make_file("empty.txt", "");
long n = copy("menu.txt", "copy.txt"); /* copy first, */
printf("menu.txt: %ld bytes copied, %s\n", n, /* then compare */
same("menu.txt", "copy.txt") ? "identical" : "DIFFERENT");
n = copy("empty.txt", "copy2.txt");
printf("empty.txt: %ld bytes copied, %s\n", n,
same("empty.txt", "copy2.txt") ? "identical" : "DIFFERENT");
fflush(stdout);
if (copy("nofile.txt", "copy3.txt") < 0) printf("nofile.txt: not copied\n");
printf("done\n");
return 0;
}
/* ── helper: 1 if the two files have exactly the same bytes ── */
int same(const char *a, const char *b) {
FILE *f = fopen(a, "rb"), *g = fopen(b, "rb");
int ok = (f != NULL && g != NULL), x, y;
while (ok) {
x = fgetc(f); y = fgetc(g);
if (x != y) ok = 0;
if (x == EOF || y == EOF) break;
}
if (f) fclose(f);
if (g) fclose(g);
return ok;
}
Real output (stdout, then the error stream):
menu.txt: 33 bytes copied, identical
empty.txt: 0 bytes copied, identical
nofile.txt: not copied
done
nofile.txt: No such file or directory
"rb"and"wb": binary mode. On Linux text and binary mode are the same, but on Windows text mode changes\r\nto\n; binary mode never changes a byte, so the same code copies pictures, PDFs and programs.- If the second
fopenfails, close the first file before returning (no leaked FILE). - A trap we met while writing this: the first version printed
copy(...)andsame(...)as two arguments of oneprintf, and the output was33 bytes copied, DIFFERENT. C does not fix the order in which a function's arguments are evaluated, and gcc evaluatedsamefirst, before the copy existed. Copy in one statement, compare in the next.
Complexity. O(n) time, one read and one write per byte. O(1) space. fgetc/fputc are buffered by the C library, so this is reasonably fast; for big files, fread/fwrite with a 4 KB buffer (practice question 3) is faster still.
Q3: Append and read student records
Problem. add_record(name, marks) adds one line like Asha 78 to marks.txt; show_records() prints every record and the average.
Think out loud.
- Add Asha 78, Ravi 85, Neha 91 → show all three, average 84.67.
- Edge cases: showing before any record exists (the file doesn't exist yet), a broken line where the marks aren't a number.
The obvious attempt: "w" and while (!feof)
#include <stdio.h>
void add_record(const char *name, int marks) {
FILE *fp = fopen("marks.txt", "w");
if (fp == NULL) { perror("marks.txt"); return; }
fprintf(fp, "%s %d\n", name, marks);
fclose(fp);
}
void show_records(void) {
FILE *fp = fopen("marks.txt", "r");
if (fp == NULL) { perror("marks.txt"); return; }
char name[50];
int marks;
while (!feof(fp)) {
fscanf(fp, "%49s %d", name, &marks);
printf("%-6s %3d\n", name, marks);
}
fclose(fp);
}
int main() {
add_record("Asha", 78);
add_record("Ravi", 85);
add_record("Neha", 91);
show_records();
return 0;
}
Real output:
Neha 91
Neha 91
marks.txt afterwards holds only Neha 91.
Why it failed
- Mode
"w"empties the file if it already exists. Eachadd_recordthrew away the earlier lines: only Neha was left. - Neha twice: after the last record,
feofis still false, sofscanfruns once more, fails (returns EOF), and leavesnameandmarksunchanged. We print the old values again.
The fix: "a" mode, and loop on what fscanf returns
#include <stdio.h>
int add_record(const char *name, int marks) {
FILE *fp = fopen("marks.txt", "a"); /* "a": add at the end */
if (fp == NULL) { perror("marks.txt"); return 0; }
fprintf(fp, "%s %d\n", name, marks);
fclose(fp);
return 1;
}
void show_records(void) {
FILE *fp = fopen("marks.txt", "r");
if (fp == NULL) { printf("no records yet\n"); return; }
char name[50];
int marks, n = 0, total = 0;
while (fscanf(fp, "%49s %d", name, &marks) == 2) { /* 2 items read */
printf("%-6s %3d\n", name, marks);
n++;
total += marks;
}
if (!feof(fp)) printf("bad record after %d good ones\n", n);
if (n > 0) printf("%d records, average %.2f\n", n, (double)total / n);
fclose(fp);
}
int main() {
show_records(); /* no file yet */
add_record("Asha", 78);
add_record("Ravi", 85);
add_record("Neha", 91);
show_records();
FILE *fp = fopen("marks.txt", "a"); /* a broken line, for testing */
if (fp != NULL) { fprintf(fp, "Kabir abc\n"); fclose(fp); }
show_records();
return 0;
}
Real output:
no records yet
Asha 78
Ravi 85
Neha 91
3 records, average 84.67
Asha 78
Ravi 85
Neha 91
bad record after 3 good ones
3 records, average 84.67
fscanf(fp, "%49s %d", name, &marks) == 2:fscanfreturns how many items it filled. We asked for two, so we continue while it returns 2. At the end of the file it returns EOF; onKabir abcit fills the name but not the number and returns 1.%49slimits the name to 49 characters, leaving room for the'\0'inchar name[50]: no buffer overflow.- After the loop,
!feof(fp)tells "stopped at a bad line" from "reached the end". %sstops at a space, so names here are one word. For full names, use a separator such as a comma andfscanf(fp, " %49[^,],%d", name, &marks).
Complexity. Adding a record: O(1). Showing n records: O(n). Space O(1): one record in memory at a time.
Complexity summary
| Question | Time | Extra space |
|---|---|---|
| Count lines, words, chars | O(n), n = bytes | O(1) |
| Copy with fgetc / fputc | O(n) | O(1) |
| Copy with fread / fwrite | O(n), fewer calls | O(buffer) |
| Add a record (append) | O(1) | O(1) |
| Show n records | O(n) | O(1) |
The one loop to remember: read first, then test (!= EOF for fgetc, == 2 for a two-item fscanf).
Common mistakes (and the real results)
| Mistake | What happens | Why | Fix |
|---|---|---|---|
while (!feof(fp)) { c = fgetc(fp); chars++; } |
42 instead of 41; 1 for an empty file | feof is true only after a failed read |
while ((c = fgetc(fp)) != EOF) |
char c = fgetc(fp); |
a 0xFF byte looks like EOF (or EOF is never seen) | EOF isn't a char value |
int c |
| words = spaces + 1 | 6 words; 1 for an empty file | spaces ≠ word breaks | count where words start (isspace) |
ignoring a last line with no \n |
2 lines instead of 3 | no newline to count | if (last != '\n') lines++; |
copy with fscanf("%s") / fprintf("%s\n") |
DIFFERENT |
%s skips whitespace |
fgetc/fputc, "rb"/"wb" |
no check after fopen |
Segmentation fault |
fopen returned NULL |
if (fp == NULL) { perror(name); ... } |
printf(..., copy(...), same(...)) |
33 bytes copied, DIFFERENT |
argument order is unspecified | separate statements |
fopen("marks.txt", "w") to add a record |
only the last record survives | "w" empties the file |
"a" |
while (!feof(fp)) { fscanf(...); printf(...); } |
the last record printed twice | fscanf failed, old values kept |
while (fscanf(...) == 2) |
%s into char name[50] |
a long name overflows the array | no limit | %49s |
Your turn: the longest line (solution)
Problem. Print the number and the length of the longest line of a file. poem.txt → line 1, 15 characters. An empty file → no lines.
Idea. Read with fgetc, count the current line's length, check it at every \n and reset; after the loop, a last line without \n still counts. Don't use fgets into a fixed array: a line can be longer than any array.
#include <stdio.h>
#include <stdlib.h>
void make_file(const char *name, const char *text) { /* test input */
FILE *fp = fopen(name, "w");
if (fp == NULL) { perror(name); exit(1); }
fputs(text, fp);
fclose(fp);
}
void longest(const char *name) {
FILE *fp = fopen(name, "r");
if (fp == NULL) { perror(name); return; }
int c, line = 0, len = 0, best = -1, best_line = 0, any = 0;
while ((c = fgetc(fp)) != EOF) {
any = 1;
if (c == '\n') { /* a line ends */
line++;
if (len > best) { best = len; best_line = line; }
len = 0;
} else {
len++;
}
}
if (any && len > 0) { /* last line with no '\n' */
line++;
if (len > best) { best = len; best_line = line; }
}
if (line == 0) printf("%s: no lines\n", name);
else printf("%s: line %d, %d characters\n", name, best_line, best);
fclose(fp);
}
int main() {
make_file("poem.txt", "Twinkle twinkle\nlittle star\nhow I wonder");
make_file("empty.txt", "");
make_file("last.txt", "ab\nabc\nabcdefg");
longest("poem.txt");
longest("empty.txt");
longest("last.txt");
return 0;
}
Real output:
poem.txt: line 1, 15 characters
empty.txt: no lines
last.txt: line 3, 7 characters
last.txt checks the trap: its longest line is the last one, which has no \n. O(n) time, O(1) space.
Practice questions (with solutions)
1. Count how many times a word appears in a file
Here %s is exactly right, because we want words.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void make_file(const char *name, const char *text) {
FILE *fp = fopen(name, "w");
if (fp == NULL) { perror(name); exit(1); }
fputs(text, fp);
fclose(fp);
}
int count_word(const char *name, const char *word) {
FILE *fp = fopen(name, "r");
if (fp == NULL) { perror(name); return -1; }
char w[100];
int n = 0;
while (fscanf(fp, "%99s", w) == 1) /* here %s is right: we WANT words */
if (strcmp(w, word) == 0) n++;
fclose(fp);
return n;
}
int main() {
make_file("poem.txt", "Twinkle twinkle\nlittle star\nhow I wonder\nwhat you are\nTwinkle twinkle little star\n");
printf("Twinkle: %d\n", count_word("poem.txt", "Twinkle"));
printf("star: %d\n", count_word("poem.txt", "star"));
printf("moon: %d\n", count_word("poem.txt", "moon"));
return 0;
}
Real output:
Twinkle: 2
star: 2
moon: 0
O(n) time, O(1) space (one word at a time). strcmp is case-sensitive: twinkle is a different word from Twinkle.
2. Merge two files into a third
#include <stdio.h>
#include <stdlib.h>
void make_file(const char *name, const char *text) {
FILE *fp = fopen(name, "w");
if (fp == NULL) { perror(name); exit(1); }
fputs(text, fp);
fclose(fp);
}
int append_file(FILE *out, const char *name) { /* copy one file into out */
FILE *in = fopen(name, "rb");
if (in == NULL) { perror(name); return 0; }
int c;
while ((c = fgetc(in)) != EOF) fputc(c, out);
fclose(in);
return 1;
}
int main() {
make_file("a.txt", "Asha 78\nRavi 85\n");
make_file("b.txt", "Neha 91\n");
FILE *out = fopen("all.txt", "wb");
if (out == NULL) { perror("all.txt"); return 1; }
append_file(out, "a.txt");
append_file(out, "b.txt");
fclose(out);
FILE *fp = fopen("all.txt", "r"); /* show the result */
if (fp == NULL) { perror("all.txt"); return 1; }
int c;
while ((c = fgetc(fp)) != EOF) putchar(c);
fclose(fp);
return 0;
}
Real output:
Asha 78
Ravi 85
Neha 91
O(n + m) time for files of n and m bytes, O(1) space.
3. Copy a file with fread and fwrite
fread(buf, 1, size, in) reads up to size bytes and returns how many it really read; fwrite returns how many it wrote, which must equal what we asked.
#include <stdio.h>
#include <stdlib.h>
long copy(const char *src, const char *dst) {
FILE *in = fopen(src, "rb");
if (in == NULL) { perror(src); return -1; }
FILE *out = fopen(dst, "wb");
if (out == NULL) { perror(dst); fclose(in); return -1; }
char buf[4096]; /* 4 KB at a time */
size_t got;
long total = 0;
while ((got = fread(buf, 1, sizeof buf, in)) > 0) {
if (fwrite(buf, 1, got, out) != got) { perror(dst); total = -1; break; }
total += (long)got;
}
fclose(in);
fclose(out);
return total;
}
int main() {
FILE *fp = fopen("big.bin", "wb"); /* 10000 bytes: 0, 1, ..., 255, 0, 1, ... */
if (fp == NULL) { perror("big.bin"); return 1; }
for (int i = 0; i < 10000; i++) fputc(i % 256, fp);
fclose(fp);
printf("%ld bytes copied\n", copy("big.bin", "big2.bin"));
return 0;
}
Real output (and cmp big.bin big2.bin reports no difference):
10000 bytes copied
The test file holds every byte value 0..255, including 0 and 255, the bytes text functions trip over.
Quick quiz
/* hi.txt holds 3 bytes: 'h' 'i' '\n' */
FILE *fp = fopen("hi.txt", "r");
int n = 0;
while (!feof(fp)) {
fgetc(fp);
n++;
}
printf("%d\n", n);
What does it print? (A) 2 (B) 3 (C) 4 (D) It never stops
Answer
(C) 4. After the third byte, feof is still false. The fourth fgetc fails and returns EOF, and only then does feof become true; n was already counted.
Interview questions
- What does
fopenreturn when it fails, and how do you find out why? NULL;perror(orstrerror(errno)) gives the reason. - Difference between
"w","a"and"r+"?"w"creates or empties;"a"writes at the end;"r+"reads and writes an existing file without emptying it. - Why is
while (!feof(fp))wrong?feofreports the end only after a read has failed, so the body runs once with a failed read. - Why must
fgetc's result be stored in anint? It returns 0..255 or EOF; acharcan't hold all 257 values. - What does
fscanfreturn? The number of items filled, or EOF at the end before anything was read. - Text vs binary mode? On Windows text mode converts
\r\n; binary mode never changes bytes. Use binary for copying. - What happens if you forget
fclose? Buffered data may not be written if the program crashes, and the program can run out of open files. - How do you count lines that don't end in
\n? Track the last character; if the file is non-empty and doesn't end in\n, add one. - How would you copy a 2 GB file fast?
fread/fwritewith a large buffer; check every return value. - Is the order of evaluation of function arguments defined in C? No, it's unspecified; never rely on it.
Glossary
| Term | Meaning | Example |
|---|---|---|
| File | Named data stored on disk that survives the program | poem.txt |
FILE * (file pointer) |
A handle that fopen gives you to use a file |
FILE *fp |
| Mode | How a file is opened | "r", "w", "a", "rb", "wb" |
| Append | Add at the end without removing anything | fopen(name, "a") |
| Binary mode | Bytes are read and written unchanged | "rb", "wb" |
| EOF | A special int (here -1) meaning "end of file" |
fgetc at the end |
feof |
True only after a read failed at the end | the extra-character bug |
fgetc / fputc |
Read / write one byte | the copy loop |
fscanf return value |
How many items were filled | == 2 |
perror |
Prints a message and the reason for the last error | missing.txt: No such file or directory |
| Error stream (stderr) | A second output, for error messages | perror writes there |
| Output buffer | Memory where printed text waits before it's written | why fflush(stdout) before a crash |
fflush |
Writes the buffer out now | fflush(stdout) |
| Whitespace | Space, tab, newline and similar | isspace(c) |
isspace |
Tests for whitespace (<ctype.h>) |
the word counter |
| Word | A run of non-whitespace characters | little, star |
wc |
The Linux command that counts lines, words and bytes | wc poem.txt |
| NULL pointer | A pointer to nothing | a failed fopen |
| Segmentation fault | The OS stops a program that touches memory it doesn't own | fscanf(NULL, ...) |
| Undefined behaviour | Code the C standard gives no meaning to | reading through NULL |
| Unspecified order of evaluation | C doesn't say which argument is computed first | printf(..., copy(), same()) |
| Buffer overflow | Writing past the end of an array | %s into char name[50] without a limit |
| Record | One entry of related data | Asha 78 |
fread / fwrite |
Read / write blocks of bytes | practice question 3 |
| O(n) | Work that grows with the file size | counting, copying |
| O(1) space | A fixed amount of memory, whatever the file size | the counters |
Summary
- Count:
int c,while ((c = fgetc(fp)) != EOF), count words where they start withisspace, and add a line if the file doesn't end in\n. O(n), O(1). - Copy: every byte with
fgetc/fputc(orfread/fwrite), in"rb"/"wb", and check everyfopenfor NULL withperror. O(n), O(1). - Records:
"a"appends,"w"empties; loop onfscanf(...) == 2, never on!feof. O(1) to add, O(n) to show. - Never rely on the order in which a function's arguments are evaluated.
Next episode: Tricky output questions, the placement round: printf's return value, sizeof on arrays vs pointers, static variables, switch fall-through, signed vs unsigned comparison, and i++ + ++i.