[英]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
Here's my code for copying the file. 这是我复制文件的代码。
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;
}
and here is the code for my structre: 这是我的structre的代码:
typedef struct song{
string title;
string artist;
string album;
string genre;
float rating;
struct song *next;
}song_t;
also, typedef char string[30]; 另外,typedef char string [30];
i can't seem to copy the data from files to the structure in main. 我似乎无法将数据从文件复制到main中的结构。 Can anyone help me with this?
谁能帮我这个?
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;
}
There are a few problems with the above code that may not be problems depending on you input file format, but here goes: 上面的代码有一些问题可能不是问题,具体取决于您输入的文件格式,但这里有:
First, you control the while
loop with a fgets
that throws a line away. 首先,你用一个抛出一条线的
fgets
来控制while
循环。 Are you certain that's what you wanted. 你确定这是你想要的吗?
Secondly, you should always check the return value from malloc
in case it fails. 其次,您应该始终检查
malloc
的返回值,以防它失败。
Thirdly, you're assuming that each field is on its own line. 第三,你假设每个领域都是独立的。 You should confirm that.
你应该确认一下。
Fourth, you're not really inserting correctly into a linked list. 第四,你并没有真正插入到链表中。 If your intent is to insert new items at the start of the list, change:
如果您打算在列表的开头插入新项目,请更改:
temp->next == NULL;
temp = temp->next;
into: 成:
temp->next == head;
head = temp;
and ensure you call it as: 并确保将其称为:
actualHead = ReadFile (actualHead);
to update the head
pointer correctly. 正确更新
head
指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.