我试图在 while 循环中继续读取文件。该循环调用另一个函数,该函数获取文件作为参数,读取它并返回读取的内容。然而,第一个函数总是“从一开始”调用第二个函数,这会导致只读取第一行的循环。 这是两个函数的代码:
void pgList_read(FILE *fp, pgList_t pgList){
pg_t pg;
while(pg_read(fp, &pg) == 1){
pg_print(stdout, &pg, NULL);
pgList_insert(pgList, pg);
}
}
int pg_read(FILE *fp, pg_t *pgp){
if(fscanf(fp, "%s %s %s ", pgp->cod, pgp->nome, pgp->classe)){
stat_read(fp, &pgp->b_stat);
pgp->equip = equipArray_init();
return 1;
}
return 0;
}
我尝试将文件指针传递给第二个函数并在 fscanf 中使用它,但它也不起作用
您可以尝试将 while 循环放入其他函数中或 尝试在第二个函数中返回 FILE* 或 在 while 循环中使用 fscanf,例如:
while( fscanf(fp,"%s %s %s",v1,v2,v3) != EOF){
// code here
}
编辑:我的意思是你可以做某事。像这样
void pgList_read(FILE *fp, pgList_t pgList){
pg_t pg;
while( !feof(pg_read(fp, &pg)) ){
pg_print(stdout, &pg, NULL);
pgList_insert(pgList, pg);
}
}
第二个函数就像这样
FILE* pg_read(FILE *fp, pg_t *pgp){
if(fscanf(fp, "%s %s %s ", pgp->cod, pgp->nome, pgp->classe) !=EOF){
// need to check you'r reading the last item trio correctly just in case
stat_read(fp, &pgp->b_stat);
pgp->equip = equipArray_init();
return fp;
}
return NULL;
}