这是我复制文件的代码。
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;
}
这是我的结构的代码:
typedef struct song{
string title;
string artist;
string album;
string genre;
float rating;
struct song *next;
}song_t;
还有, typedef 字符字符串[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
指针。
关于c - 我需要将数据从文件 "MusicLibrary.txt"复制到结构中。但是当我使用我的代码时,它不会返回任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12758203/