This code is a portion of a FTP client that I have developed:
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;
}
I would like to implement the percentage of the downloaded file but I have some problems. I’ve tried with this method:
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;
}
but I don’t like it because when the transfer starts, “20%” is immediately printed and also because if I remove the \n from 20%%\n – 40%%\n etc., the values are printed at the end of the transfer and not immediately.
How can I develop better code?
1 Answer