Skip to content

Instantly share code, notes, and snippets.

@JesseEisen
Created June 15, 2016 13:54
Show Gist options
  • Save JesseEisen/710fdce0971dc489965f352542865a48 to your computer and use it in GitHub Desktop.
Save JesseEisen/710fdce0971dc489965f352542865a48 to your computer and use it in GitHub Desktop.
'tail -n' implemented by C
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define DEFLINES 10
#define MAXLEN 100
int getlines(char *s, int len){
int c, i;
for(i = 0; i< len -1 &&(c = getchar()) != EOF && c != '\n'; ++i){
s[i] = c;
}
if(c == '\n'){
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
void show_result(char **res, int end, int total,int isfull)
{
int i;
if(isfull == 0){
for( i = 0; i< end; i++)
printf("%s",res[i]);
}else{
if(end == total){
for(i = 0; i < end; i++)
printf("%s",res[i]);
}else{
for(i = end; i<total; i++)
printf("%s",res[i]);
for(i = 0; i< end; i++){
printf("%s",res[i]);
}
}
}
}
int main(int argc,char **argv){
char **lineptr; //save the result
char line[MAXLEN]; //save the readline
int end; //the actually end
int total; //total line
int len;
int isfull;
if(argc == 1){
total = DEFLINES;
}else if(argc == 2 && (*++argv)[0] == '-'){
total = atoi(argv[0]+1);
}else{
printf("Usage: tail [-n]");
exit(1);
}
lineptr = malloc(sizeof(char *) * total);
end = 0;
isfull = 0;
while((len = getlines(line,MAXLEN)) > 0){
if(end <= total){
lineptr[end] = malloc(sizeof(char) * len);
strcpy(lineptr[end], line);
end++;
}else{
end = 0;
isfull = 1;
lineptr[end] = malloc(sizeof(char) * len);
strcpy(lineptr[end],line);
end++;
}
}
show_result(lineptr,end, total,isfull);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment