This is a working snippet of a while loop:
while(total_bytes_read != fsize){
while((nread = read(sockd, filebuffer, sizeof(filebuffer))) > 0){
if(write(fd, filebuffer, nread) < 0){
perror("write");
close(sockd);
exit(1);
}
total_bytes_read += nread;
if(total_bytes_read == fsize) break;
}
}
This is an example of a NON working snippet of a while loop:
while(total_bytes_read != fsize){
while((nread = read(sockd, filebuffer, sizeof(filebuffer))) > 0){
if(write(fd, filebuffer, nread) < 0){
perror("write");
close(sockd);
exit(1);
}
total_bytes_read += nread;
}
}
And also this, is an example of a NON working snippet of a while loop:
while(total_bytes_read < fsize){
while((nread = read(sockd, filebuffer, sizeof(filebuffer))) > 0){
if(write(fd, filebuffer, nread) < 0){
perror("write");
close(sockd);
exit(1);
}
}
total_bytes_read += nread;
}
I would like to know why into the 2 snippet above when total_bytes_read is equal to fsize the loop won’t exit :O
Thanks in advance!
The outer loop in snippets 2 and 3 will not exit because the inner loop does not exit: the
total_bytes_read != fsizeloop never gets a chance to check its continuation condition.Snippet 1 works fine, because you check the same condition inside the nested loop, and break out if the limiting count has been reached.
You can combine both conditions into a single loop, like this: