Search code examples
clinuxioc99

Writing double to stdout using the write function


I store n double numbers in binary format as follows:

int main(int argc, char** argv)
{
    int k = atof(argv[1]);
    int fd = open("./gen-double.bin", O_CREAT | O_WRONLY | O_TRUNC, 0666);

    for(double i = 1.0; i < k; i *= 1.333)
    {
        write(fd, &i, sizeof(double));
    }

    return 0;
}

I was wondering if it was possible to output them using the write function: I tried the following code which gives me funky characters:

int main(int argc, char** argv)
{
    int fd = open("./gen-double.bin", O_RDONLY);
    double i;

    while(read(fd, &i, sizeof(double)))
    {
        write(STDOUT_FILENO, &i, sizeof(double));
        printf("\n");
    }    

    return 0;
}

Do I need to convert these numbers to char?

Edit

Done

int main(int argc, char** argv)
{
    int     fd = open("./gen-double.bin", O_RDONLY);
    double  i;
    int     res;
    char    buffer[11];

    while(read(fd, &i, sizeof(double)))
    {
        res = sprintf(buffer, "%.10f", i);
        buffer[11] = '\0';
        write(STDOUT_FILENO, buffer, 11);
        printf("\n");
    }    

    return 0;
}

Solution

  • It seems that you're writing the binary encoding of the double into STDOUT.

    printf (which you would normally use) decodes the binary double into text before sending it to STDOUT.

    For example: 1.0 is encoded in memory as 3ff0 0000 0000 0000 (see this).

    While the text 1.0 is the characters '1', '.' and '0' which are encoded as 0x31, 0x2E, 0x30 (from here).