【发布时间】:2015-06-11 18:39:29
【问题描述】:
晚上好 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);
}
【问题讨论】:
-
您需要
fflush和rewind或fseek。也fclose(myfile);filling:fclose呼叫两次。