ch1-Print longest line (getline)

Chapter_1     Exercise_1-15     args Exercise_1-16







longest.c     K&R, p. 29         download


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

#define MAXLINE 1000 // maximum input line size

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

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; // initialize
while((len = getLine(line, MAXLINE)) > 0)
{ // line containing only '\n' not empty
if (len > max)
{
max = len;
copy(longest, line);
}
}
if (max > 0) // there was a line
{
printf("%s", longest);
if (longest[max-1] != '\n')
{putchar('\n');} // line may not end with '\n'
}

return 0;
}

// getLine(): read a line into s[], return length
int getLine(char s[], int lim) // return 0 at EOF
{
int c = EOF; // initialize
int i;
// 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

return i; // max(i) == (lim-1), assuming (lim-1) > 0
}

// 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 longest.c -o longest
./longest // input from the keyboard
The sky is gray
A storm is coming
Rain fills the rivers // Enter, then EOF (Ctrl+D in Linux, Ctrl+Z+Enter in Windows)
Rain fills the rivers

./longest < longest.c // source file
Rain fills the rivers // Enter, then EOF (Ctrl+D in Linux, Ctrl+Z+Enter in Windows)

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





Warning:  You should not print the contents of a binary file in a terminal window because it may be interpreted as commands, which may influence the behavior of the operating system. Here, ELF signals a binary file (Executable_and_Linkable_Format).









Chapter_1     Exercise_1-15     args BACK_TO_TOP Exercise_1-16



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo