Search code examples
cbuffersystemfile-descriptor

C read() and write() while loop


Here is example code:

int nbajt; int buf[];

 // we opened file and get descriptor fd

 while ((nbajt = read(fd, buf, 5)) > 0) {
        if (write(fd2, buf, nlbajt) == -1) {
            perror("ERROR");
            exit(1);
        }
    } 

I don't understand how it is working when we use while loop. How many times this loop will proceed? (times of the lengs of buf?). Will nbajt has only values of 1 or 0 + buf file position will be changing 1 place after each loop step? So in first step we have nlbajt = 1 and we take buf first position char and then write it to fd2?. On the end we have nlbajt==0 so it means it's end of file? I would be grateful for checking if i am wrong.My main concern is how nbajt value is changing. How it is diffrent for this attitude:

nbajt = read(fd, buf, 5));
write(fd2, buf, sizeof(a));

Solution

  • The read() has the below prototype:

    int  read(  int  handle,  void  *buffer,  int  nbyte );
    

    It returns number of bytes successfully read . 0 when EOF is reached.-1 when there is an error.

    Yes nlbajt = 0 means EOF here.