Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. /*PROGRAM TO PRINT THE LAST 'n' LINES OF INPUT
  2. *CHECKLILST:
  3. * -stores the lines as an array of pointers
  4. * -accepts n from the command line
  5. */
  6.  
  7. #include<stdio.h>
  8. #include<string.h>
  9. #include<stdlib.h>
  10.  
  11. #define SIZE 100 /*maximum no. of characters in each line*/
  12. #define DMAX 5 /*default value of no. lines to print*/
  13.  
  14. void readlines(int *, int *, char **);
  15. void printlines(int *, int *, char **);
  16.  
  17. int main(int argc, char *argv[])
  18. {
  19. int start= 0; /*stores the location of the oldest line read*/
  20. int n= (argc==1)?DMAX:atoi(argv[1]+1);
  21. printf("Value of n is %dnn", n);
  22. char *line[n];
  23. int i;
  24. for(i=0; i<n; i++)
  25. line[i]= NULL;
  26. readlines(&start, &n, line);
  27. printlines(&start, &n, line);
  28. return EXIT_SUCCESS;
  29. }
  30.  
  31. /*readlines(): reads lines from a file and stores it as required*/
  32. void readlines(int *start, int *n, char *line[])
  33. {
  34. char cline[SIZE];
  35. printf("Enter the name of the filen");
  36. char filename[20];
  37. scanf("%s", filename);
  38. FILE *fin= fopen(filename, "r");
  39.  
  40. int i= 0;
  41. while(fgets(cline, SIZE, fin)) {
  42. if(line[i%*n]!=NULL)
  43. free(line[i%*n]);
  44. line[i%*n]= strdup(cline);
  45.  
  46. ++i;
  47.  
  48. if(*start+1==*n) {
  49. *start= 0;
  50. continue;
  51. }
  52. if(i>=*n)
  53. ++*start;
  54. }
  55. --*start; /*compensate for the extra updation*/
  56. fclose(fin);
  57. }
  58.  
  59. /*printlines(): prints the lines*/
  60. void printlines(int *start, int *n, char *line[])
  61. {
  62. int i=*start;
  63. do {
  64. printf("%d. %sn", i, line[i]);
  65. if(i==*n-1)
  66. i= 0;
  67. else
  68. ++i;
  69. }
  70. while(i!=*start && line[i]!=NULL);
  71. }
  72.  
  73. do {
  74. printf("%d. %sn", i, line[i]);
  75. if(i==*n-1)
  76. i= 0;
  77. else
  78. ++i;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement