此代码是我开发的FTP客户端的一部分:
for(size_to_receive = file_size; size_to_receive > 0;){
nread = read(f_sockd, filebuffer, size_to_receive);
if(nread < 0){
perror("read error on retr");
close(fd);
return -1;
}
if(write(fd, filebuffer, nread) != nread){
perror("write error on retr");
close(fd);
return -1;
}
size_to_receive -= nread;
}
我想实现下载文件的百分比,但我有一些问题。我试过这种方法:
for(size_to_receive = file_size; size_to_receive > 0;){
nread = read(f_sockd, filebuffer, size_to_receive);
tx += nread;
printf("%d%%\n", (tx * 100 / file_size));
fflush(NULL);
if(nread < 0){
perror("read error on retr");
close(fd);
return -1;
}
if(write(fd, filebuffer, nread) != nread){
perror("write error on retr");
close(fd);
return -1;
}
size_to_receive -= nread;
}
但我不喜欢它,因为当传输开始时,“20%”会立即打印,而且如果我从
\n
-20%%\n
中删除40%%\n
,值会在传输结束时打印,而不是立即打印。如何开发更好的代码?
最佳答案
for (size_to_receive = file_size; size_to_receive > 0;) {
nread = read(f_sockd, filebuffer, size_to_receive);
tmp_xc += nread;
printf("%d%%\r", (tmp_xc * 100 / file_size));
fflush(NULL);
}