i wrote a tiny version of tail command using a large buffer statically allocated but, in a second time, i found another version in which i use a bidimensional array dynamically allocated.
here is the first version
/*my tiny tail, it prints the last 5 line of a file
*/
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#define MAXSIZE 5000
void flush(char* buff,int n);
int main(int argc,char*argv[]){
int i,n,fd,count;
char buff[MAXSIZE];
if (argc<2){printf("no file name inserted\n"),exit(1);}
else if(argc>2) printf("too many parameters\n"),exit(1);
else{
if((fd=open(argv[1],O_RDONLY))<0) {perror("open error"),exit(1);}
/*file opened in readonly mode*/
lseek(fd,-1,SEEK_END);/*the offset points the char before the end of file*/
count=0;
i=MAXSIZE;
flush(buff,MAXSIZE);/*clean the buffer*/
while(count!=5){
if((read(fd,&buff,sizeof(char)))<0) perror("read error"),exit(1);
if(buff=='\n') ++count;/*count increments when the program meet a new line */
--i;
lseek(fd,-2,SEEK_CUR);/*read puts the offset one char forward */
}
for(n=i;n<MAXSIZE-1;++n)
printf("%c",buff[n]);
printf("\n");
close(fd);
}
return 0;
}
void flush(char* buff,int n){
int i;
for(i=0;i<n;++i) buff=0;
}
the question is:
in program like this with large buffer is better dynamic allocation or static?
thanks
(PS: sorry for my bad english :o)