简体   繁体   中英

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:

typedef struct song{
string title;
string artist;
string album;
string genre;
float rating;
struct song *next;
}song_t;

also, typedef char string[30];

i can't seem to copy the data from files to the structure in 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. Are you certain that's what you wanted.


Secondly, you should always check the return value from malloc in case it fails.


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.


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM