Chapter 7: Input and Output covers the standard I/O library in depth — formatted output with printf, formatted input with scanf, file access with fopen/fclose, line I/O with fgets/fputs, and error handling via stderr. The chapter also introduces variable-argument functions (stdarg.h) through a worked minprintf example. The exercises range from practical utilities (a case-converter, a file comparator, a multi-file grep, a paginator) to implementing stripped-down versions of printf and scanf yourself. These are worked solutions to all 9 exercises. Each solution compiles cleanly with gcc -ansi -Wall.
Book: The C Programming Language, 2nd Ed — Kernighan & Ritchie | All chapters index
Exercises
Exercise 7-1. Write a program that converts upper case to lower or lower case to upper, depending on the name it is invoked with, as found in argv[0].
Solution to Exercise 7-1
Exercise 7-2. Write a program that will print arbitrary input in a sensible way. As a minimum it should print non-graphic characters in octal or hex (according to local custom), and fold long lines.
Solution to Exercise 7-2
Exercise 7-3. Revise minprintf to handle more of the other facilities of printf.
Solution to Exercise 7-3
Exercise 7-4. Write a private version of scanf analogous to the private printf described in this section.
Solution to Exercise 7-4
Exercise 7-5. Rewrite the postfix calculator of Chapter 4 to use scanf and/or sscanf to do the input and number conversion.
Solution to Exercise 7-5
Exercise 7-6. Write a program to compare two files, printing the first line where they differ.
Solution to Exercise 7-6
Exercise 7-7. Modify the pattern finding program of Chapter 5 to take its input from a set of named files or, if no files are named, from the standard input. Should the file name be printed when a match is found?
Solution to Exercise 7-7
Exercise 7-8. Write a program to print a set of files, starting each new file on a new page, with a title and a running page count for each file.
Solution to Exercise 7-8
Exercise 7-9. Functions like isupper can be implemented to save space or to save time. Explore both possibilities.
Solution to Exercise 7-9
See also: K&R C — All Chapters Index | Complete C Programs List