Understanding read() Operation in C?

I have this code:

int fd = open(filename, O_RDONLY);
char buf[len];
size_t count =0;
while (count < len){
    size_t_nbytes = read (fd, buf+len, len-count);
    if(nbytes==0){
        len=count;
         break;
     }
    count +=nbytes;
}

The part I donĀ“t understand is the len-count in the read() function. len-count is the size of the block I would like to read. Which in the first loop is len. So everything I want to read. Can I just replace it with len? The loop should probably only loop once anyway? Thanks for any help.

Answers


While it "probably" should loop once, don't bet on it, better just handle it:

int fd = open(filename, O_RDONLY);
char buf[len];
size_t count =0;
while (count < len){
    size_t_nbytes = read (fd, buf+count, len-count);
                               //  ^^  use count instead of len
    if(nbytes==0){
         break;
     } else if (nbytes == -1) {
         perror("read");
         break;
     }
    count +=nbytes;
}

Now, the first iteration, if e.g. len is 100, the read call becomes

 read (fd, buf+0, 100-0);

If this happened to read 50 bytes, the next round becomes

  read (fd, buf+50, 100-50);

Which is exactly what you'd want.


Need Your Help

Polynomial Solver for iOS?

objective-c ios math

I'm writing an app where I have three data points and need to derive the parabola that connects them. Basically I need this result to extrapolate other data points. Just like a Trendline in Excel w...