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?
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
whileloop with afgetsthat throws a line away. Are you certain that’s what you wanted.Secondly, you should always check the return value from
mallocin 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:
into:
and ensure you call it as:
to update the
headpointer correctly.