exc/k&r/01-a-tutorial-introduction/01-16.c

64 lines
1.4 KiB
C

#include <stdio.h>
#define MAXLINE 1000
int mygetline(char line[], int maxline);
void copy(char to[], char from[]);
/* print longest input line */
int main()
{
int len, max; /* current, max lenght */
char line[MAXLINE+1], longest[MAXLINE+1]; /* current, longest line; +1 for \0 */
max = 0;
while ((len = mygetline(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0) {
printf("%d ", max);
if (max <= MAXLINE && longest[max-1] == '\n') {
longest[max-1] = '\\';
printf("\n%sn\n", longest);
} else if (max <= MAXLINE) {
printf("\n%s\n", longest);
} else
printf("(first %d chars)\n%s...\n", MAXLINE, longest);
} else
printf("No lines found\n");
return 0;
}
/* mygetline : read part of line smaller than lim-1 into s, return length */
int mygetline(char s[], int maxline)
{
int c, i;
for (i=0; (c=getchar()) != EOF; ++i) {
if (i < maxline)
s[i] = c;
if (c == '\n') {
++i;
break;
}
}
if (i < maxline)
s[i] = '\0';
else
s[maxline] = '\0';
return i;
}
/* copy : copy 'from' to 'to'; assume 'to' is big enough */
void copy(char to[], char from[])
{
int i;
for(i = 0; (to[i] = from[i]) != '\0'; ++i)
;
}