0

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.

Karina Kozarova
  • 1,145
  • 3
  • 14
  • 29

1 Answers1

2

The for loop is reading a character from the file before it ends. If there are at least 5 lines, it reads a newline the last time, and then the rest of the code starts reading from after that newline.

But if it gets to the beginning of the file without finding 5 newlines, the last read() reads the first character of the file, and the rest of the code starts reading from after that.

When *buff != '\n' you need to print that character first.

if (*buff != '\n') {
    write(STDOUT_FILENO, buff, 1);
}
count *= -1; // get abs value of bytes
count++;
while(count--){
    wres = write(STDOUT_FILENO,buff,read(fd, buff,1)); // output
}
Barmar
  • 741,623
  • 53
  • 500
  • 612