Exercise 1-16 (Long line length, getline)

Chapter_1     Exercise_1-15     Longest_line Exercise_1-17







Exercise 1-16     K&R, p. 30


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.




longline.c         download


#include <stdio.h> // for getchar(), printf(), EOF

#define MAXLINE 1000 // maximum input line size printed

long getLine(char line[], int maxline); // getline() is declared in stdio.h
// long getLine(char [], int); // alternative declaration
void copy(char to[], char from[]);
// void copy(char [], char []); // alternative declaration

// getLine() returns the size of an arbitrarily long line
// program prints longest line up to MAXLINE characters
int main()
{
long len; // current line length
long max; // maximum length seen so far
char line[MAXLINE]; // current input line
char longest[MAXLINE]; // longest line saved here

max = 0; // initialize
while((len = getLine(line, MAXLINE)) > 0)
{ // line containing only '\n' has length 1
if (len > max)
{
max = len;
copy(longest, line);
}
}
if (max > 0) // there was a line
{
printf("Length: %ld\n", max);
printf("%s\n", longest); // line may not end with '\n'
}

return 0;
}

// getLine(): read a line into s[] up to MAXLINE-1 chars, return total length
long getLine(char s[], int lim) // returns 0 at EOF
{
int c = EOF; // initialize
long i; // length of an arbitrarily long line
// getchar() is only executed if (i < (lim-1)):
for (i = 0; i < (lim-1) && (c = getchar()) != EOF && c != '\n'; i++)
{ // from 0 to lim-2; s[lim-2]='\n' or not, s[lim-1]='\0'
s[i] = c;
}
if (c == '\n') // i < (lim-1), getchar() executed
{
s[i] = c; // '\n'
i++;
}
s[i] = '\0'; // the null character ends a string

if (c != EOF && c != '\n') // i == (lim-1) > 0
{
while ((c = getchar()) != EOF && c != '\n')
{i++;}
}

return i; // max(i) can exceed lim
}

// copy(); copy from[] into to[]; assume to[] is big enough
void copy(char to[], char from[])
{
int i;

for (i = 0; (to[i] = from[i]) != '\0'; i++)
{} // ends after copying '\0'
}
/*
gcc longline.c -o longline
./longline < longline.c // source file
Length: 77
// getLine(): read a line into s[] up to MAXLINE-1 chars, return total length

./longline < longline // binary file
Length: 4824
ELF // line contains '\0', which ends copy() and printf("%s")
*/





Note:  In main() we cannot write printf("%s", longest); if (longest[max-1] != '\n') {putchar('\n');} // line may not end with '\n' because max may exceed MAXLINE. That is actually the reason getLine() returns a long instead of an int, as in the previous program (longest).









Chapter_1     Exercise_1-15     Longest_line BACK_TO_TOP Exercise_1-17



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo