2

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!

4

3 回答 3

6

片段 2 和 3 中的外部循环不会退出,因为内部循环不会退出:total_bytes_read != fsize循环永远没有机会检查其继续条件。

片段 1 工作正常,因为您检查嵌套循环的相同条件,如果已达到限制计数,则中断。

您可以将这两个条件组合成一个循环,如下所示:

while((total_bytes_read != fsize) && (nread = read(sockd, filebuffer, sizeof(filebuffer))) > 0) {
    ...
}
于 2012-07-03T13:51:34.897 回答
0

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

if(total_bytes_read == fsize) break;
于 2012-07-03T13:52:17.633 回答
0

不以这种方式编写读取循环是有原因的。(实际上,有很多。)如果您计算 fsize,然后在您阅读时文件更改大小,您的循环将永远不会终止。不要这样做!无需计算文件大小;只需读取数据,直到没有更多数据。

于 2012-07-03T14:52:54.297 回答