[英]fscanf not reading from file
我试图从我的txt文件中读取一些输入,但是我不知道为什么它没有读取...我在做什么错?
文件内容:3 1.0 0.05 0.2 0.5
阅读功能:
float * le_dados_ficheiro(char *nomeFich,int *nMoedas, float *valor)
{
FILE *f;
float *p,*q;
int i;
f = fopen(nomeFich,"r");
if(!f)
{
printf("Erro ao abrir ficheiro %s\n",nomeFich);
exit(1);
}
fscanf(f," %d %f",nMoedas,valor);//**It is empty after this**
p = malloc(sizeof(float)*(*nMoedas));
if(!p)
{
printf("Erro ao reservar memoria ... \n");
exit(1);
}
q = p;
for(i = 0; i < *nMoedas; i++)
fscanf(f," %f",q++);
fclose(f);
printf("%f - %f - %f",q[0],q[1],q[2]);//**Still empty**
return q;
}
您只是在这里打印错误的数据:
printf("%f - %f - %f", q[0], q[1], q[2]);
数组结束后的q
点。 您需要打印p
:
printf("%f - %f - %f", p[0], p[1], p[2]);
否则,如果文件的确切内容是这样,您的程序将起作用:
3 1.0
0.05 0.2 0.5
通过错误检查纠正代码:
float *le_dados_ficheiro(char *nomeFich, int *nMoedas, float *valor)
{
FILE *f;
float *p, *q;
int i;
f = fopen(nomeFich, "r");
if (!f)
{
printf("Erro ao abrir ficheiro %s\n", nomeFich);
exit(1);
}
if (fscanf(f, " %d %f", nMoedas, valor) != 2)
{
printf("Wrong file format ... \n");
exit(1);
}
p = malloc(sizeof(float)*(*nMoedas));
if (!p)
{
printf("Erro ao reservar memoria ... \n");
exit(1);
}
q = p;
for (i = 0; i < *nMoedas; i++)
{
if (fscanf(f, " %f", q++) != 1)
{
printf("Wrong file format ... \n");
exit(1);
}
}
fclose(f);
printf("%f - %f - %f", p[0], p[1], p[2]);
return q;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.