我编写了这个程序,假设将一些浮点数写入二进制文件,然后读取它并仅显示位于偶数位置的数字。现在,我很难弄清楚如何验证位置并显示其中的内容。任何人都可以看看代码并告诉我是否有任何错误,我怎么能这样显示?当 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));
}
}