[英]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.