Follow commands that write to and read from named files.
What to build
A program in which a missing file is a normal event and not a crash.
Requirements
add NAME WORDadds the word as a new line at the end of that file, creating it if needed. Print nothing.show NAMEprints each line of the file, ormissing NAMEif the file cannot be opened.count NAMEprints the number of lines, ormissing NAME.
Input
The first line has n. Each of the next n lines is a command.
Output
Only what the commands above print.
Constraints
n is from 1 to 50. Names and words have at most 20 letters.
Example
Input:
3
add a.txt hello
add a.txt world
show a.txt
Output:
hello
world
Why it works
Mode "a" adds without erasing and creates the file if it is not there, while mode "r" fails on a missing file, and that failure is what missing reports.
Examples
Example 1 · Input
3 add a.txt hello add a.txt world show a.txt
Expected output
hello world
Example 2 · Input
2 show b.txt count b.txt
Expected output
missing b.txt missing b.txt
Hints
Hint 1
Open with "a" so that existing lines are kept.
Hint 2
A read of a missing file gives NULL from fopen.
Hint 3
Write one function per command.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
#include <string.h>
void add(const char *name, const char *word) {
FILE *f = fopen(name, "a");
if (f == NULL) return;
fprintf(f, "%s\n", word);
fclose(f);
}
void show(const char *name) {
FILE *f = fopen(name, "r");
if (f == NULL) {
printf("missing %s\n", name);
return;
}
char line[50];
while (fgets(line, sizeof line, f) != NULL) {
printf("%s", line);
}
fclose(f);
}
void count(const char *name) {
FILE *f = fopen(name, "r");
if (f == NULL) {
printf("missing %s\n", name);
return;
}
char line[50];
int lines = 0;
while (fgets(line, sizeof line, f) != NULL) {
lines++;
}
fclose(f);
printf("%d\n", lines);
}
int main(void) {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
char command[10], name[21], word[21];
scanf("%9s %20s", command, name);
if (strcmp(command, "add") == 0) {
scanf("%20s", word);
add(name, word);
} else if (strcmp(command, "show") == 0) {
show(name);
} else {
count(name);
}
}
return 0;
}