Re: Division in loop

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]


Hi again...

int fd; /* RS232 serial link */
int fdp; /* file descriptor for a regular file */
struct stat stat;
size_t bytes = 0;
void *buffer; /* buffer, will be allocated */
...
    while (bytes < stat.st_size) {
        ret = read(fdp, buffer + bytes, stat.st_size - bytes);
        if (ret == -1) {
            perror("read");
            return -1;
        }
        ret = write(fd, buffer + bytes, ret);
        if (ret == -1) {
            perror("write");
            return -1;
        }
        bytes += ret;
        progress = (int) (bytes * 100) / stat.st_size;
        printf("\rcompleted: %i%%", progress);
        fflush(stdout);
    }
...

Then i see printf() never output the message until the loop has ended...
'fdp' is a file descriptor to a local file, i send it through a serial
connection (RS232),
i use a serial connection so i can practice Linux's File I/O operation
in real world ;p

the receiver can output the progress's message, but the sender (the
above code) could not...
this is the receiver codes:

...
while (bytes < size) {
        ret = read(fd, buffer + bytes, size - bytes);
        if (ret == -1) {
            perror("read");
            return -1;
        }
        ret = write(fdp, buffer + bytes, ret);
        if (ret == -1) {
            perror("write");
            return -1;
        }
        bytes += ret;

        progress = (int) (bytes * 100) / size;
        printf("\rcompleted: %i%%", progress); /* THIS NEVER OUTPUT,
UNTIL LOOP END! */
        fflush(stdout);
    }
...



On Tue, Sep 8, 2009 at 8:49 PM, Glynn Clements<glynn@xxxxxxxxxxxxxxxxxx> wrote:
>
> Tim Walberg wrote:
>
>> Maybe you want "(bytes * 100) / size"?
>
> However, if int and size_t are 32-bit, that will overflow at around
> 20 or 40 MB (20 for signed, 40 for unsigned), which isn't really all
> that much. Converting to either double or long long might be wise,
> i.e.
>
>        percent = (int)(bytes * 100.0) / size;
> or:
>        percent = (int)(bytes * 100LL) / size;
>
> --
> Glynn Clements <glynn@xxxxxxxxxxxxxxxxxx>
>
--
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html

[Linux Assembler]     [Git]     [Kernel List]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [Yosemite Campsites]     [Yosemite News]     [GCC Help]

Add to Google Powered by Linux