为什么下面的函数fscanf会出现读取错误,谢谢...

#include <stdio.h>
#include <windows.h>
#include <string.h>
#include <stdlib.h>
int func(FILE *fin)
{
char ch;
int i=0;
if(fin == NULL) //打开失败
{
puts("open file failed!");
system("pause");
return 0;
}
for(;feof(fin)==0;)
{
ch=fgetc(fin); //读取一个字符
if(ch=='\n')
i++;
}
fclose(fin);
i--;
return i;
}
void main()
{
FILE *fin;
int count1=0; //对matchings中点的个数计数
fin=fopen("matchings.txt","r");
count1=func(fin);
printf("%d\n",count1);
rewind(fin);
double *matchX1_Right=(double *)malloc(count1*sizeof(double));
double *matchY1_Right=(double *)malloc(count1*sizeof(double));
double *matchX2_Right=(double *)malloc(count1*sizeof(double));
double *matchY2_Right=(double *)malloc(count1*sizeof(double));
for (int ii=0;ii<count1;ii++)
{
fscanf(fin,"%lf %lf %lf %lf",&matchX1_Right[ii],&matchY1_Right[ii],&matchX2_Right[ii],&matchY2_Right[ii]);
if(ii==0) //验证fscanf读取是否正确!
{
printf("%lf",matchX1_Right[ii]);
}
}
free(matchX1_Right);
free(matchY1_Right);
free(matchX2_Right);
free(matchY2_Right);
return;
}

附:matching.txt
733.441 885.822 756.176 907.545
331.264 351.402 330.599 359.72
59.5066 905.803 757.576 906.369
89.2106 918.055 106.939 905.047
651.124 782.969 655.263 792.525
56.9743 839.622 87.9941 827.466
50.26 853.373 771.095 863.284
162.857 791.939 177.546 784.756
61.8751 841.21 92.5041 829.165
304.999 337.74 296.65 346.029
321.218 390.012 267.382 389.773
310.954 389.182 264.602 389.398

第1个回答  2013-08-09
不懂你func函数想用来干嘛。
我调试了下,在申请内存的时候malloc出错,count1的值等于-1,申请内存的时候转换成一个正的long型数了,这个数多大自己清楚,当然是不可能分配成功的。追问

谢谢您的回答。可能是我粘的部分程序没有说清楚问题,我的意思是:首相txt文档中的个数是不清楚的,func函数就是要确定其行数;申请动态内存的目的就是为了要建立一个个数为变量的数组;最后要把txt文件中的字符串以数组的形式存储下来,一边后续的操作(相当于MATLAB中对矩阵的操作)。

相似回答