+#include <stdio.h>
+
+/* Exercise 1-16. Revise the main routine of the longest-line program
+ so it will correctly print the length of arbitrarily long input
+ lines, and as much as possible of the text. */
+
+/* Strat: Modify mygetline() to read a char and increment `i` even if
+ `i<lim-1` is `FALSE`, until `EOF` or `\n` is encountered. However,
+ only store char to mygetline()'s output array if `i<lim-1` is TRUE;
+ otherwise, only increment `i`. Then, after `EOF` or `\n`
+ encountered, terminate line with `\n\0` so `\0` occupies last
+ element of `line[]` (i.e. 'line[MAXLINE-1]'). Return `i`.
+
+ Print `i` before contents of `line[]` array to communicate length
+ of string stored in `line[]`.
+*/
+
+#define MAXLINE 1000 /* maximum input line size */
+
+int mygetline(char line[], int maxline); /* 'my-' to avoid name collision */
+void copy(char to[], char from[]);
+
+/* print longest input line */
+int main() {
+ int len; /* current line length */
+ int max; /* maximum length seen so far */
+ char line[MAXLINE]; /* current input line */
+ char longest[MAXLINE]; /* longest line saved here */
+
+ max = 0;
+ while ((len = mygetline(line, MAXLINE)) > 0)
+ if (len > max) {
+ max = len;
+ copy(longest, line);
+ }
+ if (max > 0) /* there was a line */
+ printf("%03d:%s", max, longest);
+ return 0;
+};
+
+/* mygetline: read a line into s, return length v2 */
+int mygetline(char s[], int lim) {
+ int c, i;
+
+ for (i=0; (c=getchar())!=EOF && c!='\n'; ++i) {
+ if (i<lim-1)
+ /* Store char c to s if c not a newline or EOF */
+ s[i] = c;
+ };
+
+ if (i < lim-1) {
+ /* Case:lim will not be exceeded */
+ if (c == '\n') {
+ /* Handle c is '\n' */
+ s[i] = c;
+ ++i;
+ };
+ s[i] = '\0';
+ } else {
+ /* Case:lim will be exceeded */
+ /* Terminate s with '\n\0' */
+ s[lim-2] = '\n';
+ ++i;
+ s[lim-1] = '\0';
+ };
+ return i;
+};
+
+/* copy: copy 'from' into 'to'; assume to is big enough */
+void copy(char to[], char from[]) {
+ int i;
+
+ i = 0;
+ while ((to[i] = from[i]) != '\0')
+ ++i;
+};