Search code examples
coperating-systemfwrite

print first 3 lines of a file using system function write


I am trying to print the first 3 lines using the system function write in .

I have the following code:

ssize_t wresult = 0; 
ssize_t res;
ssize_t rresult = 0;
char buff[1];
int count = 0;

while((rresult = read(fd, buff,1))!= 0 ) 
{
    while(wresult != rresult){
        ssize_t res = 0;
        res = write(STDOUT_FILENO,buff+wresult,rresult-wresult);
        if(res < 0) return -1;
        wresult += res;
        count++;
        if(count == 3) break;
    }
}

However, the output is not what I want - it outputs the whole file (more than 10 lines).
How do I print just the first 3 lines.


Solution

  • The function write() will write a number of bytes to file (or stdout). You need to figure out where the end of the lines are.

    There are a number of problems from the code you have here. The variable count is not being set to any value and so it will always be 0.

    Also, from the code you have here you're reading from a 1 byte buffer. That would cause a crash.