我以二进制格式存储n
个双数,如下所示:
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;
}
我想知道是否可以使用write
函数输出它们:
我尝试了以下代码,它给了我时髦的角色:
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;
}
我是否需要将这些数字转换为char
?
完成
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;
}