[英]I need to copy data from a file, “MusicLibrary.txt” to a strucutre. But when I'm using my code, it doesn't return anything
这是我复制文件的代码。
song_t *ReadFile(song_t *head){
FILE *input;
input = fopen("MusicLibrary.txt", "r");
song_t *temp = head;
string title;
string artist;
string album;
string genre;
string store;
string buffer;
while(fgets(buffer, MAXSIZE, input) != NULL){
temp = (song_t *)malloc(sizeof(song_t));
fgets(temp->title, MAXSIZE, input);
fgets(temp->artist, MAXSIZE, input);
fgets(temp->album, MAXSIZE, input);
fgets(temp->genre, MAXSIZE, input);
fgets(store, MAXSIZE, input);
temp->rating = atof(store);
temp->next == NULL;
temp = temp->next;
}
fclose(input);
return head;
}
这是我的structre的代码:
typedef struct song{
string title;
string artist;
string album;
string genre;
float rating;
struct song *next;
}song_t;
另外,typedef char string [30];
我似乎无法将数据从文件复制到main中的结构。 谁能帮我这个?
while(fgets(buffer, MAXSIZE, input) != NULL){
temp = (song_t *)malloc(sizeof(song_t));
fgets(temp->title, MAXSIZE, input);
fgets(temp->artist, MAXSIZE, input);
fgets(temp->album, MAXSIZE, input);
fgets(temp->genre, MAXSIZE, input);
fgets(store, MAXSIZE, input);
temp->rating = atof(store);
temp->next == NULL;
temp = temp->next;
}
上面的代码有一些问题可能不是问题,具体取决于您输入的文件格式,但这里有:
首先,你用一个抛出一条线的fgets
来控制while
循环。 你确定这是你想要的吗?
其次,您应该始终检查malloc
的返回值,以防它失败。
第三,你假设每个领域都是独立的。 你应该确认一下。
第四,你并没有真正插入到链表中。 如果您打算在列表的开头插入新项目,请更改:
temp->next == NULL;
temp = temp->next;
成:
temp->next == head;
head = temp;
并确保将其称为:
actualHead = ReadFile (actualHead);
正确更新head
指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.