I am trying to output the content of a file using system calls. The code is working nice until we have a file that contains only one line. in that case, the output is the line without the first char. Where does this char get lost?
ssize_t rres,wres;
char buff[1];
off_t offset;
int fd = open("tester.txt",O_CREAT | O_RDWR , 0664 );
int line_count = 5;
for(count = 0;line_count != 0;count--){
offset = lseek(fd, count, SEEK_END);
rres = read(fd,buff,1);
if(rres < 0){
return -1;
}
if(*buff =='\n') line_count--;
}
count *= -1; // get abs value of bytes
count++;
while(count--){
wres = write(STDOUT_FILENO,buff,read(fd, buff,1)); // output
}
I am trying to output the last 5 lines of a file. But if I have less than 5 lines, the first char is not outputed.