Skip to content

Instantly share code, notes, and snippets.

@EdgeCaseBerg
Created July 5, 2013 03:40
Show Gist options
  • Save EdgeCaseBerg/5931479 to your computer and use it in GitHub Desktop.
Save EdgeCaseBerg/5931479 to your computer and use it in GitHub Desktop.
Code Listing 1.9 from The C Programming Language by Brian W. Kernighan, Dennis M. Ritchie​. Modified slightly to not include the newline of a line in the character sequence modified by the ourgetline function.
#include <stdio.h>
#define MAXLINE 1000
int ourgetline(char line[], int maxline);
void copy(char to[], char from[]);
main(){
int len, max;
char line[MAXLINE];
char longest[MAXLINE];
max =0;
while ((len = ourgetline(line,MAXLINE)) > 0){
if(len > max){
max = len;
copy(longest,line);
}
}
if(max > 0){
printf("%s\n", longest);
}
return 0;
}
int ourgetline(char s[], int lim){
int c,i;
for(i=0; i < lim-1 && (c=getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if(c == '\n'){
s[i] = '\0';
++i;
}
return i;
}
void copy(char to[], char from[]){
int i;
i=0;
while((to[i] = from[i]) != '\0')
++i;
}
@EdgeCaseBerg
Copy link
Author

$ cc longestline.c
$ ./a.out < somefile.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment