简体   繁体   English

从文件中读取双二进制数据

[英]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. 我正在尝试从文件中读取二进制数据,将其转换为double类型的数字并将其打印到屏幕上。 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. 我可以使它适用于字节和整数数据,但是当我尝试将其转换为双精度时,我得到的都是0。 There is as much 0 as the should be numbers of type double, but those numbers in binary form are not zeros. double类型的数字应为0,但二进制形式的数字不是零。

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. 就像我说的那样,当我使用sizeof(int)* 1和(int)buffer时,它适用于整数,也适用于字节数据,但不适用于double数据。

You are using a buffer that is 1 byte wide. 您正在使用一个1字节宽的缓冲区。 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. 它与int一起工作的事实只是误报,因为您正在读取sizeof(int)并将其复制到sizeof(char)缓冲区中。

If you want to read a double then use a double as destination buffer, eg: 如果要读取一个double则将double用作目标缓冲区,例如:

double buffer;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM