Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*PROGRAM TO PRINT THE LAST 'n' LINES OF INPUT
- *CHECKLILST:
- * -stores the lines as an array of pointers
- * -accepts n from the command line
- */
- #include<stdio.h>
- #include<string.h>
- #include<stdlib.h>
- #define SIZE 100 /*maximum no. of characters in each line*/
- #define DMAX 5 /*default value of no. lines to print*/
- void readlines(int *, int *, char **);
- void printlines(int *, int *, char **);
- int main(int argc, char *argv[])
- {
- int start= 0; /*stores the location of the oldest line read*/
- int n= (argc==1)?DMAX:atoi(argv[1]+1);
- printf("Value of n is %dnn", n);
- char *line[n];
- int i;
- for(i=0; i<n; i++)
- line[i]= NULL;
- readlines(&start, &n, line);
- printlines(&start, &n, line);
- return EXIT_SUCCESS;
- }
- /*readlines(): reads lines from a file and stores it as required*/
- void readlines(int *start, int *n, char *line[])
- {
- char cline[SIZE];
- printf("Enter the name of the filen");
- char filename[20];
- scanf("%s", filename);
- FILE *fin= fopen(filename, "r");
- int i= 0;
- while(fgets(cline, SIZE, fin)) {
- if(line[i%*n]!=NULL)
- free(line[i%*n]);
- line[i%*n]= strdup(cline);
- ++i;
- if(*start+1==*n) {
- *start= 0;
- continue;
- }
- if(i>=*n)
- ++*start;
- }
- --*start; /*compensate for the extra updation*/
- fclose(fin);
- }
- /*printlines(): prints the lines*/
- void printlines(int *start, int *n, char *line[])
- {
- int i=*start;
- do {
- printf("%d. %sn", i, line[i]);
- if(i==*n-1)
- i= 0;
- else
- ++i;
- }
- while(i!=*start && line[i]!=NULL);
- }
- do {
- printf("%d. %sn", i, line[i]);
- if(i==*n-1)
- i= 0;
- else
- ++i;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement