0

我编写了这个程序,假设将一些浮点数写入二进制文件,然后读取它并仅显示位于偶数位置的数字。现在,我很难弄清楚如何验证位置并显示其中的内容。任何人都可以看看代码并告诉我是否有任何错误,我怎么能这样显示?当 ftell、fgetpos 等在二进制文件中使用时,它们的行为方式究竟发生了什么变化,我也有点困惑。任何答案将不胜感激。这是代码:

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

void read(float *p,int n);

void main()
{
    int n;
    float *p,nr;
    char name[20];
    fpos_t poz;
    printf("How many numbers would you like to have in your array?\n");
    scanf("%d",&n);
    if(!(p=(float*)malloc(n*sizeof(float))))
    {
        printf("Allocation unsuccessful!\n");
        return;
    }

    read(p,n);
    printf("Give the name of the binary file\n");
    scanf("%s",name);

    FILE *f;

    if((f=fopen(name,"w+b"))==NULL)
    {
        printf("The file could not be reached for writing\n");
        return;
    }
    for(int i=0; i<n; i++)
    {
        fwrite((p+i),sizeof(float),1,f);
        fclose(f);
    }

    if((f=fopen(name,"rb"))==NULL)
    {
        printf("The file could not be opened:\n");
        return;
    }

    printf("The numbers at positions 0,3,6 etc. are:\n");
    while ((fread(&nr,sizeof(float),1,f)==1))
    {
        poz=ftell(f);
        if((poz%2)==0)
        {
            printf("%f",nr);
        }
    }
    fclose(f);
    if(p)
        free(p);
    system("pause");
}

void read(float *p,int n)
{
    printf("Introduce the series of numbers:\n");
    for(int i=0; i<n; i++)
    {
        printf("Give the number %d:",i+1);
        scanf("%f",(p+i));
    }
}
4

1 回答 1

2

我第一眼发现的错误可能更多:

void main()

main应该返回int。参数列表应该是void. 您的编译器可能仍然采用您的版本:

int main(void)

下一个问题:

for(int i=0; i<n; i++)
{
    fwrite((p+i),sizeof(float),1,f);
    fclose(f);
}

在第一次迭代后关闭文件,然后尝试再次写入。您应该在完成后关闭文件,而不是在第一次写入之后:

for(int i=0; i<n; i++)
{
    fwrite((p+i),sizeof(float),1,f);
}
fclose(f);

这部分没有做你期望它做的事情:

poz=ftell(f);
if((poz%2)==0)
{
    printf("%f",nr);
}

ftell返回以字节为单位的位置。每个float通常占用 4 个字节。所以在这一点上,位置将永远是平的。您想检查它是否除以 8 或更好的两倍大小float

poz=ftell(f);
if(( poz % (2*sizeof(float)) == 0)
{
    printf("%f",nr);
}

但是,使用计数器代替会更实用:

for(int poz=0; fread(&nr,sizeof(float),1,f)==1; poz++)
{
    if((poz%2)==0)
    {
        printf("%f",nr);
    }
}

这应该是C还是C++?代码看起来像 C,但你将它标记为 C++,而且这个包含在 C: 中也是错误的:#include <string>应该是#include <string.h>.

要使用system("pause");,您需要#include <stdlib.h>. 该行本身不可移植,您应该以不同的方式处理它,请参阅上面的评论。

于 2014-01-12T10:19:28.393 回答