Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #define DEFAULT_STRING_NUM 10
- #define MAXLEN 1000
- #define MAXLINES 5000
- char *lineptr[MAXLINES];
- int getline(char *, int);
- char *smartalloc(int n, char *begin);
- int readlines(char *linestack[], int tail_num);
- void writelines(char *lineptr[], int tail_num, int nlines);
- void writespecific(char *lineptr[]);
- int main(int argc, char *argv[])
- {
- int num, nlines;
- if (argc == 3 && strcmp(*(argv+1),"-n") == 0) {
- num = atoi(*(argv+2));
- if (num < 1) {
- printf("usage: 'tail -n COUNT_LINES' \n");
- return -1;
- }
- else if (num > MAXLINES) {
- printf("n must be in {1..%d}\n",MAXLINES);
- return -1;
- }
- }
- else if (argc == 1)
- num = DEFAULT_STRING_NUM;
- else {
- printf("usage: 'tail -n COUNT_LINES' \n");
- return -1;
- }
- if ((nlines=readlines(lineptr, num)) >= 0) {
- num = (num > nlines) ? nlines : num ; /* if in stdio lines less, than user want (num) */
- writelines(lineptr, num, nlines);
- return 0;
- } else {
- printf("error: input too big to tail\n");
- return -1;
- }
- }
- /* readlines: */
- int readlines(char *lineptr[], int tail_num)
- {
- int len; /* length string getted from getline */
- int nlines = 0; /* total count strings ( <= tail_num )*/
- char *p; /* pointer to current free position (returned by smartalloc) */
- char *leftpos = NULL; /* pointer to beginning interest block (use in smartalloc) */
- char *rightpos = NULL; /* pointer to end interest block (calculate as p+len) */
- char line[MAXLEN]; /* current string */
- while ((len = getline(line, MAXLEN)) > 0) {
- if ((p = smartalloc(len+1, leftpos)) == NULL) { /* if buffer overfull */
- return -1;
- }
- else {
- /* check is `memory moved`? if next pointer not "next" */
- if (rightpos+1 > p) {
- /* moving interest pointers value */
- for (int i = 0; i < tail_num; i++)
- lineptr[nlines-i-1] -= rightpos - p + 1;
- /* (rightpos - p + 1) - moving 'diff' (in pointers) */
- }
- /* copying string */
- line[len] = '\0'; /* delete \n in line */
- strcpy(p, line);
- lineptr[nlines++] = p;
- if (nlines <= tail_num)
- leftpos = lineptr[0]; /* first element */
- else
- leftpos = lineptr[nlines-tail_num]; /* first interest element */
- rightpos = p + len;
- }
- }
- return nlines;
- }
- void writelines(char *lineptr[], int tail_num, int nlines)
- {
- for (int i = 0; i < tail_num; i++)
- printf("%s\n",lineptr[nlines-tail_num+i]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement