K&R C Programs Exercise 5-17

Exercise 5-17. Add a field-handling capability, so sorting may be done on fields within lines, each field sorted according to an independent set of options. (The index for this book was sorted with -df for the index category and -n for the page numbers.) Fields are whitespace-delimited columns. The syntax -k<field>[flags] selects a 1-based field …

K&R C Programs Exercise 5-15

Exercise 5-15. Add the option -f to fold upper and lower case together, so that case distinctions are not made during sorting; for example, a and A compare equal. Add a fold flag. When set, the comparison function converts both characters to lowercase before comparing. The key: don’t modify the strings themselves — do the …

K&R C Programs Exercise 5-16

Exercise 5-16. Add the -d (directory order) option, which makes comparisons only on letters, numbers and blanks. Make sure it works in conjunction with -f. Directory order ignores punctuation and control characters — only alphanumeric characters and spaces are considered. The comparison function skips non-directory characters in both strings simultaneously, then compares the next significant …

K&R C Programs Exercise 5-14

Exercise 5-14. Modify the sort program to handle a -r flag, which indicates sorting in reverse (decreasing) order. Be sure that -r works with -n. The K&R sort from Section 5.11 calls qsort with a comparison function strcmp. Adding -r requires the comparison function to negate its result. The cleanest approach: add a global flag …

K&R C Programs Exercise 5-13

Exercise 5-13. Write the program tail, which prints the last n lines of its input. By default, n is 10, say, but it can be changed by an optional argument, so that tail -n prints the last n lines. The program should behave rationally no matter how unreasonable the input or the value of n. …

K&R C Programs Exercise 5-12

Exercise 5-12. Extend entab and detab to accept the shorthand entab -m +n to mean tab stops every n columns, starting at column m. Choose convenient (for the user) default behavior. Two new argument forms extend the programs from Exercise 5-11: -m sets the starting column and +n sets the interval. So detab -4 +3 …