简体   繁体   English

while循环不会退出C

[英]while loop won't exit C

This is a working snippet of a while loop : 这是while循环工作片段

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循环的NON工作片段的示例:

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循环的NON工作片段的示例:

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 我想知道为什么当total_bytes_read等于fsize时进入上述2个片段中,循环不会退出: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. 代码片段2和3中的外部循环不会退出,因为内部循环不会退出: total_bytes_read != fsize循环永远不会有机会检查其继续条件。

Snippet 1 works fine, because you check the same condition inside the nested loop, and break out if the limiting count has been reached. 片段1正常工作,因为您检查了嵌套循环的相同条件,并且在达到限制计数时中断。

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. (实际上,有很多。)如果计算fsize,然后文件在读取时更改大小,则循环将永远不会终止。 Don't do this! 不要这样! There is no need to compute the file size; 无需计算文件大小; just read data until there is no more. 只是读取数据,直到没有更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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