从《The.C.Programming.Language.2Nd.Ed 》5.13题出发 。Exercise 5-13. Write the program tail, which prints the last n lines of its input. By default, n is set to 10, let us say, but it can be changed by an optional argument so that tail -n prints the last n lines. The program should behave rationally no matter how unreasonable the input or the value of n. Write the program so it makes the best use of available storage; lines should be stored as in the sorting program of Section 5.6 , not in a two-dimensional array of fixed size.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAXLINES 10000
#define MAXLENGTH 1000
int main(int argc, char * argv[])
{
int tail_n = 10;
char * inputs[MAXLINES];
char line[MAXLENGTH];
if( argc > 1 && argv[1] != NULL )
{
if( argv[1][0] == '-' )
{
tail_n = atoi( &argv[1][1] );
}
}
int i = 0;
while(fgets(line, MAXLENGTH, stdin) != NULL && i < MAXLINES)
{
char * tmp = (char *)malloc( strlen(line) * sizeof(char) + 1 );
strcpy(tmp, line);
inputs[i] = tmp;
i++;
}
int j = 0;
for(; j<i-(tail_n+1); j++){}
for(; j<i; j++){ printf("%s",inputs[j]);free(inputs[j]); }
return 0;
}