[英]Why is this code not able to read contents from a file into a linked list?
I am unable to understand what the problem is as it isn't giving the correct output我无法理解问题所在,因为它没有提供正确的 output
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node*next;
};
void traversal(struct node*ptr){
while(ptr!=NULL){
printf("Element is: %d\n",ptr->data);
ptr=ptr->next;
}
}
void read(struct node*head){
FILE*file;
int val;
struct node*cur=(struct node*)malloc(sizeof(struct node));
head=cur=NULL;
file=fopen("list.txt","r");
while(fscanf(file,"%d",&val)!=EOF){
struct node*ptr=(struct node*)malloc(sizeof(struct node));
ptr->data=val;
ptr->next=NULL;
if(head==NULL){
head=cur=ptr;
}
else{
cur=cur->next=ptr;
}
}
fclose(file);
}
int main(){
struct node* head;
//Allocate memory for linked list nodes in heap
head=(struct node*)malloc(sizeof(struct node));
read(head);
traversal(head);
}
The contents of the file is该文件的内容是
3 3个
5 5个
6 6个
1 1个
3 3个
The output gives infinite number of lines with not the correct values output 给出了无数行,但值不正确
Without getting into the implementation of read()
, head
will remain the same since read()
is not modifying it but a copy.在不进入
read()
的实现的情况下, head
将保持不变,因为read()
不是修改它而是一个副本。 You're also nullifying the allocated memory which result in memory leaks.您还将使分配的 memory 无效,这会导致 memory 泄漏。
Since there is no point in allocating head
outside read()
, I suggest you define it inside to make things more clean, and then return it.由于在
read()
之外分配head
没有意义,我建议您在内部定义它以使事情更干净,然后返回它。 Something of this sort:这种东西:
struct node *read_file() {
FILE *file;
int val;
struct node *prv = NULL;
struct node *head = (struct node *)calloc(1, sizeof(struct node));;
if (head == NULL) {
return NULL;
}
file = fopen("list.txt", "r");
if (fscanf(file, "%d", &val) != EOF) {
head->data = val;
prv = head;
}
while(fscanf(file, "%d", &val) != EOF){
struct node *curr = (struct node *)calloc(1, sizeof(struct node));;
curr->data = val;
if (prv)
prv->next = curr;
prv = curr;
}
fclose(file);
return head;
}
int main(){
struct node *head = read_file();
traversal(head);
}
Don't forget to free the nodes at the end.不要忘记在最后释放节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.