Luki
Luki

Reputation: 419

Reading double binary data out of file

I am trying to read binary data out of file, convert it to numbers of type double and print it onto screen. I can get this to work for byte and integer data, but all I get when I try to convert it to doubles are 0s. There is as much 0 as the should be numbers of type double, but those numbers in binary form are not zeros.

int input_fd = open("nameoffile",O_RDONLY);
size_t ret_in;
char buffer = 0;
while((ret_in = read (input_fd,&buffer,sizeof(double)*1)) >0){
    printf("%f ", (double)buffer);
}
printf("\n");
close(input_fd);

As I said this works for integers when I use sizeof(int)*1 and (int)buffer and also for byte data but not for double data.

Upvotes: 0

Views: 362

Answers (1)

Jack
Jack

Reputation: 133619

You are using a buffer that is 1 byte wide. The fact that it's 'working' with int is just a false positive since you are reading sizeof(int) and copying them into a sizeof(char) buffer.

If you want to read a double then use a double as destination buffer, eg:

double buffer;

while((ret_in = read (input_fd, &buffer, sizeof(double))) >0) {
    printf("%f ", (double)buffer);
}

Upvotes: 2

Related Questions