[Exercise] Exercise 5-13. Write the program tail -n page 118

User avatar

Topic author
BJT
Site Admin
Site Admin
Posts: 141
Joined: Thu Apr 20, 2017 4:43 pm
Instruction: University Student
Gender:
Age: 27
Venezuela

Exercise 5-13. Write the program tail -n page 118

Post by BJT » Sat May 06, 2017 10:06 pm

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.


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define NumPtr 100
  6.  
  7. char *lineptr[NumPtr];
  8.  
  9. #define MAXLINE 1000
  10.  
  11. char line[MAXLINE];
  12.  
  13. size_t get_line(char* f_line, int n);
  14.  
  15. #define MAXALLOC 5000
  16. char buf_alloc[MAXALLOC];
  17. char *p_alloc=buf_alloc;
  18.  
  19. char* alloc(char*);
  20.  
  21. int main(int argc, char* argv[])
  22. {
  23.     int n=5;
  24.  
  25.     while(--argc>0)
  26.     {
  27.         if(*(*++argv)=='-')
  28.             n=atoi(*(argv)+1);
  29.     }
  30.  
  31.     unsigned int len;
  32.     int i=0;
  33.     while((len=get_line(line,MAXLINE))>0)
  34.     {
  35.         if((lineptr[i++]=alloc(line))==NULL)
  36.             break;
  37.     }
  38.  
  39.     for(int i=0; i<n; i++)
  40.         printf("%s\n",lineptr[i]);
  41.  
  42.     return EXIT_SUCCESS;
  43. }
  44.  
  45. size_t get_line(char* f_line, int n)
  46. {
  47.     int c;
  48.     size_t size=(size_t)f_line;
  49.  
  50.     while(((size_t)f_line-size)<n && (c=getchar())!=EOF && c!='\n')
  51.         *f_line++=c;
  52.  
  53.     *(f_line)='\0';
  54.  
  55.     return (size_t)f_line-size;
  56. }
  57.  
  58. char* alloc(char* s)
  59. {
  60.     char* p_end = buf_alloc+MAXALLOC-1;
  61.     size_t len=strlen(s)+1;
  62.  
  63.     if(p_alloc+len<p_end) //There is space in allof buffer
  64.     {
  65.         strcpy(p_alloc,s); //insert buffer
  66.         p_alloc+=len;
  67.         return p_alloc-len;
  68.     }
  69.     else
  70.         return NULL;
  71. }

input

Code: Select all

./c -6
Hello  
i
am
a
program
running
at
Linux
:)
output

Code: Select all

Hello
i
am
a
program
running
word count: 310

Link:
BBcode:
HTML:
Hide post links
Show post links

Who is online

Users browsing this forum: No registered users and 1 guest