Are you a student of Uttara Computers?
/*
write a program that displays last n lines of file.
By default, n should be 5.
But your program should accept an optional argument (like -8).
Use standard input if input file is not specified.
*/
#include<stdio.h>
#define NUMBER_OF_LINES 5
int main(argc, argv) int argc; char *argv[];{
char *filename,character;
void *abc;
int num_lines=0,N_Lines_To_Print = NUMBER_OF_LINES;
FILE *fd;
// Process the filename
// filename is not given
if(argc < 2){
printf("Enter the filename :");
filename = (char *)malloc(sizeof(char) * 255);
scanf("%s",filename);
}
// filename or option if given
if(argc == 2){
if(argv[1][0] == '-'){
N_Lines_To_Print = atoi(++argv[1]);
printf("Enter the filename :");
filename = (char *)malloc(sizeof(char) * 255);
scanf("%s",filename);
}
else
filename = argv[1];
}
// when both filename and option is given
if(argc == 3){
if(argv[1][0] == '-'){
N_Lines_To_Print = atoi(++argv[1]);
filename = argv[2];
}
else{
N_Lines_To_Print = atoi(++argv[2]);
filename = argv[1];
}
}
// file open check
if((fd = fopen(filename,"r")) == NULL){
printf("Unable to open the file\n");
return 1;
}
// count the number of lines in the file.
while(fread(&abc,1,1,fd)){
character =(char *)abc;
if(character == '\n'){
num_lines++;
}
}
// get the value of the number of lines not to be printed
fseek(fd,0L,SEEK_SET);
if(num_lines > N_Lines_To_Print)
num_lines -= N_Lines_To_Print;
else
num_lines = 0;
// start printing the file
while(fread(&abc,1,1,fd)){
character = (char *)abc;
if(!(num_lines)){
printf("%c",character);
}
else if(character == '\n')
num_lines--;
}
return 0;
}
--- In [email protected], "Paul Herring" <[EMAIL PROTECTED]>
wrote:
>
> On 11/16/06, PREM KRISHNAN <[EMAIL PROTECTED]> wrote:
> > Hi,
> > I nedd a c program which will print the last 10 lines of a file.
>
> Use 'tail'
>
> --
> PJH
>
> #700847 +(1920)- [X]
>
> andyg721: i think it was on CNN
> andyg721: Condoleeza Rice went to Asia
> andyg721: the headline was RICE IN ASIA
>