【发布时间】:2016-06-24 14:11:47
【问题描述】:
大家好,我在尝试打开文件时遇到问题。在我尝试读取现有文本文件的函数中,初始化文件指针后,我仍然收到错误“无法打开文件”,这是代码:
FILE * fp;
fp = NULL;
fp=fopen("results.txt","r");
if(fp==NULL){
printf("error!");
exit(1);
}
使用调试器,我可以看到 fp 按照要求初始化为 NULL。在下一个订单中,我可以看到它的值更改为“0x751d9c68”。 所以现在它不是NULL,但程序仍然打印错误。
PS:我使用相同的代码在另一个程序中打开另一个文件(有效):fp 的初始值为 NULL,然后将其更改为 '0x751d9c68'(是的,它在两个程序中具有相同的值),但这一次有效,因为 fp 实际上与 NULL 不同。
PPS:我正在使用 Codelite,如果有帮助的话。
编辑:添加 printf("%p\n", fp);打印这个“751D9C68”
Atleta * leggiRisultati (char fileName [], int * dim){FILE * fp; int count, i;
Atleta temp;
fp = NULL;
fp=fopen(fileName,"r");
printf("%p\n", fp);
if(fp==NULL){
perror("Error");
}
while (fscanf (fp, "%s%s%d%d%d", temp.cod, temp.nome, &temp.tN, &temp.tB, &temp.tC)== 5)
count ++;
rewind (fp);
Atleta * atl = (Atleta*) malloc(count * sizeof(Atleta));
for (i=0; i<count; i++){
int nr = fscanf(fp, "%s%s%d%d%d",atl[i].cod, atl[i].nome, &atl[i].tN, &atl[i].tB, &atl[i].tC);
//just controlling if the reading is done properly
if (nr < 4) {
printf ("cannot read the file %s",fileName);
exit (1);
}
} fclose(fp);
return atl;
}
然后我在这个 main 中使用这个函数
int main (){ int dim; Atleta * a; int i;
a = leggiRisultati("risultati.txt", &dim);
for (i =0; i<dim;i++){
stampaRisultato(a[i]);}
return 0;
}
“stampaRisultato”打印刚刚读取的文件的一行,“Atleta”是一个定义为的结构:
typedef struct {
char cod[5];
char nome[21];
int tN, tB, tC;
}Atleta;
最后,是的,文本文件与我的可执行文件位于同一目录中,是的,我有权打开该文件,该文件包含一定数量的行,每行包含 2 个字符串和 3 个 int。
【问题讨论】:
-
鉴于您的代码打印的是
error!而不是cannot open the file,我认为您没有向我们展示与失败相关的所有内容。 -
请发帖Minimal, Complete, and Verifiable example。您确定该文件存在并且可读吗?
-
那么该文件是否存在于您当前的工作目录中?你有访问权限吗?
-
我不相信你。在某处添加
printf("%p\n", fp)。 -
拨打
strerror获取错误原因