fscanf未从文件中读取
我试图读取一些输入从我的txt文件,但我不知道为什么它不读取。。。 我做错了什么 文件内容: 3 1.0 0.05 0.20.5 要读取的函数:fscanf未从文件中读取,c,file,scanf,C,File,Scanf,我试图读取一些输入从我的txt文件,但我不知道为什么它不读取。。。 我做错了什么 文件内容: 3 1.0 0.05 0.20.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("Er
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:
否则,您的程序将正常工作,提供文件的确切内容如下:
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;
}
格式现在更好了,…请显示文件的准确逐字内容。为什么您在询问失败的fscanf时没有对其返回值进行编码检查并报告它告诉您的内容?我已经尝试过检查,但它没有给出错误,您没有。读入man fscanf:成功时返回值,这些函数返回成功匹配和分配的输入项目数;在早期匹配失败的情况下,该值可以小于规定值,甚至为零。Michael Walz,即使两个变量都是指针,我是否应该这样做?
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;
}