I have a task to rewrite the Unix system function tail. My algorithm works in the following way:
I lseek to the end of the file, enter a loop, move the file descriptor a bit back, read a couple of bytes, and if I find any new lines, I increase the counter. Once, I get 10 new lines ( I think it should be 11, but the thing is not finished yet and this works for me for now ), I leave the loop.
If the file has less than 10 new lines, I get into an infinite loop, because of the way I wrote it.
Is there a way to see if I have reached the beginning of the file, so I can leave the loop then?
Code :
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main (int argc, char *argv[])
{
int fd;
off_t offset = 10;
size_t size = 10;
unsigned char buff[10];
int new_line_counter = 0;
off_t total_offset = 0;//dont mind this
fd = open("a.txt", O_RDONLY);
if (fd == -1)
{
perror("open");
return 1;
}
lseek(fd,0,SEEK_END);
while (new_line_counter < 10)
{
lseek(fd,-offset,SEEK_CUR);
total_offset+=10;//dont mind this
for(int i = 0; i<10;i++)
{
if(buff[i]=='\n')
{
if(new_line_counter==10)break;
new_line_counter++;
//printf("%d",new_line_counter);
}
}
read(fd,buff,size);
lseek(fd,-offset,SEEK_CUR);
}
}