简体   繁体   中英

while loop won't exit C

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 != fsize loop 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:

while((total_bytes_read != fsize) && (nread = read(sockd, filebuffer, sizeof(filebuffer))) > 0) {
    ...
}

因为您删除了终止循环的中断

if(total_bytes_read == fsize) break;

There's a reason not to code read loops this way. (Actually, there are many.) If you compute fsize and then the file changes size while you are reading, your loop will never terminate. Don't do this! There is no need to compute the file size; just read data until there is no more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM