tail program in c

Solutions on MaxInterview for tail program in c by the best coders in the world

showing results for - "tail program in c"
Alessia
21 Sep 2017
1/* Write a Program tail, which prints the last n lines of its input. By default n is 10. let us say; but it can be changed
2by an optional argument so that tail -n */
3
4#include<stdio.h>
5#include<stdlib.h>
6#include<string.h>
7
8#define DEFLINES 10 /* default # of lines to print */
9#define LINES   100 /* maximum # of lines to print */
10#define MAXLEN  100 /* maximum length of an input line */
11
12void error(char *);
13int mgetline(char *,int);
14
15/* print the last n lines of the input */
16
17int main(int argc,char *argv[])
18{
19    char *p;
20    char *buf;  /* pointer to the large buffer */
21    char *bufend;   /* end of the large buffer */
22
23    char line[MAXLEN];
24    char *lineptr[LINES];   /* pointer to lines read */
25    
26    int first,i,last,len,n,nlines;
27
28    if( argc == 1)
29        n = DEFLINES;
30
31    else if(argc ==2 && (*++argv)[0] == '-')
32        n = atoi(argv[0]+1);
33    else
34        error("Usage: tail [-n]");
35
36    if( n < 1 || n > LINES)
37            n = LINES;
38
39    for(i = 0; i < LINES; i++)
40            lineptr[i] = NULL;
41
42    if(( p = buf = malloc(LINES * MAXLEN)) == NULL)
43        error("tail: cannot allocate buf");
44    bufend = buf + LINES + MAXLEN;
45
46    last = 0;
47    nlines = 0;
48
49    while((len = mgetline(line,MAXLEN)) > 0)
50    {
51        if(p+len+1 >= bufend)
52            p = buf;
53        lineptr[last] = p;
54
55        strcpy(lineptr[last],line);
56        if(++last >= LINES)
57            last = 0;
58
59        p += len + 1;
60        nlines++;
61    }
62
63    if( n > nlines)
64        n = nlines;
65
66    first = last - n;
67
68    if(first < 0)
69        first += LINES;
70    
71    for(i= first; n-- > 0;i = (i+1) % LINES)
72        printf("%s",lineptr[i]);
73
74    return 0;
75}
76
77/* error: print error messages and exit */
78
79void error(char *s)
80{
81    printf("%s\n",s);
82    exit(1);
83}
84
85/* mgetline: read a line into s and return length */
86
87int mgetline(char s[],int lim)
88{
89    int c,i;
90    
91    for(i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n';++i)
92        s[i] = c;
93    if ( c == '\n')
94    {
95        s[i] = c;
96        ++i;
97    }
98
99    s[i] = '\0';
100    return i;
101}
102
103