在C中编程,读取二进制文件并仅以浮动表示法输出零而不是文件内容

时间:2017-12-06 02:18:52

标签: c

我对C语言不太熟悉或者真的编写代码。我试图读取二进制文件并将其输出到屏幕。我正在使用fread和fopen,因为这些与二进制文件一起使用。我有这个代码编译,但当我运行我的代码./a.out data1我只得到0.0000。文件内容为4,1.1,2.2,3.3,4.4。这是应该输出的。 1.1000 2.2000 3.3000 4.40000只有花车。我怀疑问题是我没有正确地将文件中的值传递给数组。我将不胜感激任何帮助或评论。我的代码如下。

#include <stdio.h>
#include <malloc.h>

int main (int argc, char *argv[])
{
    FILE *ifile;
    int cnt, i;
    float *fptr;
    fptr = malloc (cnt * sizeof (float));
    ifile = fopen (argv[1], "rb");
    fread (fptr, sizeof (float), cnt, ifile);
    printf ("%f\n", *fptr);
}

// new code that works
#include <stdio.h>
#include <malloc.h>

int main (int argc, char *argv[])
{
    FILE *ifile;
    int cnt, i;
    float *fptr;
    ifile = fopen (argv[1], "rb");
    if (fread (&cnt, sizeof (int), 1, ifile) != 1) {
        printf ("%d\n", cnt);
    }
    fptr = malloc (cnt * sizeof (float));
    fread (fptr, sizeof (float), cnt, ifile);
    for (i = 0; i < cnt; i++) {
        printf ("%f\n", *fptr[i]);
    }
}

1 个答案:

答案 0 :(得分:0)

您没有在任何地方设置cnt,因此您可以阅读未指定数量的浮点数,这些浮点数可能正确也可能不正确。如果我硬编码到4并使用包含4个浮点数的二进制数据文件,它可以正常工作:

#include <stdio.h>
#include <malloc.h>
int main (int argc, char *argv[]){
    FILE *ifile;
    int cnt = 4, i;
    float *fptr;
    fptr= malloc(cnt*sizeof(float));
    ifile=fopen(argv[1], "rb");
    fread(fptr, sizeof(float), cnt, ifile);
    printf("%f\n", *fptr);
    printf("%f\n", fptr[1]);
    printf("%f\n", fptr[2]);
    printf("%f\n", fptr[3]);
}

运行程序:

$ ./test-prog data
1.100000
2.200000
3.300000
4.400000
$ hd data
00000000  cd cc 8c 3f cd cc 0c 40  33 33 53 40 cd cc 8c 40  |...?...@33S@...@|
00000010