晚上好,StackOverFlow。 我输入了一个使用列表和文件来管理地址簿的代码,现在我遇到了函数 fgets() 的问题。 在过程 print_file() 中,我使用 fgets() 从文件中读取一行并将其存储到最多 200 个字符的字符串中。调试我的代码时,我注意到该文件已流行,但在我使用 fgets() 提取该行并将其存储到字符串中后,字符串结果为空。接下来,我发布了过程 print_file() 和过程 filling(),它们通过列表的节点普及了文件。有人可以帮助我吗?
void print_file(FILE* myfile, int num){
char contact[200];
int i=0;
while(i<num){
fgets(contact, 200, myfile);
i++;
printf("%d) %s", i, contact);
}
fclose(myfile);
}
void filling(FILE* myfile){
list_struct* l; node_struct* new_node;
node_struct* tempnode;
t_contact temp;
int n_contacts=0, i=0;
printf("\n*****The file will be filled by a list*****\n");
l=made_list(); //creating new list
if(l!=NULL){
printf("\nList successfully created\n");
}
printf("How many contacts do you want to add to the list? ");
scanf("%d", &n_contacts);
for(i=1;i<=n_contacts;i++){
printf("NAME > ");
scanf("%s", temp.name);
printf("SURNAME > ");
scanf("%s", temp.surname);
printf("TELEPHONE > ");
scanf("%s", temp.telephone);
printf("E-MAIL > ");
scanf("%s", temp.email);
printf("\n");
new_node = made_node(temp); //creating new node
add_node(l, new_node);
}// end for --> the list has been popularized
tempnode = l->head;
while(tempnode!=NULL){
fprintf(myfile, "%s %s %s %s\n", tempnode->content.name, tempnode->content.surname, tempnode->content.telephone, tempnode->content.email);
tempnode=tempnode->next;
}
print_file(myfile, n_contacts);
fclose(myfile);
}
最佳答案
按照您编写的方式,将调用 fgets() 从文件末尾开始读取。您可以使用 fseek() 定位到文件的开头。
关于C:对文件使用 fgets(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30788864/