Write the following two functions maintaining a database of entries of type song in a file.(see .h file for the definition of the struct song)
int add_song(const char* file_name, const song s);
The function gets the name of a file, and a song. If the song is not in the file, the function adds
it to the file and returns 1. Otherwise, the function does not modify the file and returns 0.
song* find_song(const char* file_name, const char* title);
The function gets the name of a file and a title of a song. It searches the file for the song with
the given title. If a song is found, it returns a pointer to the song with all the details. If not found,
the function returns NULL. You may assume the song titles are unique.
What I have tried:
typedef struct {
char* title;
char* artist;
int year;
} song;
song* find_song(const char* file_name, const char* title) {
FILE *fp;
fp = fopen(file_name, "r");
if (fp == NULL) {
return NULL;
}
char song_title[100];
char song_artist[100];
int song_year;
while (fscanf(fp, "%s %s %d", song_title, song_artist, &song_year) != EOF) {
if (song_title == title) {
song *song_pointer = malloc(sizeof(song));
song_pointer->title = song_title;
song_pointer->artist = song_artist;
song_pointer->year = song_year;
return song_pointer;
}
fclose(fp);
return NULL;
}
}
int add_song(const char* file_name, const song s) {
FILE *fp;
fp = fopen("file_name", "a");
if(fp == NULL){
fclose(fp);
return 0;
}
song *song_pointer = find_song(file_name, s.title);
if (song_pointer != NULL){
fprintf(fp,"%s %s %d\n", s.title, s.artist, s.year);
fclose(fp);
return 1;
}else {
fclose(fp);
return 0;
}
}
int main(){
song bd = {"All Along the Watchtower", "Bob Dylan", 1968};
song jj = {"Mercedes Benz", "Janis Joplin", 1971};
song lz = {"Stairway to Heaven", "Led Zeppelin", 1971};
int tmp;
tmp = add_song("songs.db", bd);
if (tmp == 1)
printf("Q4-1 ok\n");
else
printf("Q4-1 ERROR : expected 1, return = %d\n", tmp);
tmp = add_song("songs.db", jj);
if (tmp == 1)
printf("Q4-2 ok\n");
else
printf("Q4-2 ERROR : expected 1, return = %d\n", tmp);
tmp = add_song("songs.db", lz);
if (tmp == 1)
printf("Q4-3 ok\n");
else
printf("Q4-3 ERROR : expected 1, return = %d\n", tmp);
tmp = add_song("songs.db", jj);
if (tmp == 0)
printf("Q4-4 ok\n");
else
printf("Q4-4 ERROR : expected 0, return = %d\n", tmp);
song *s_mb = find_song("songs.db", "Mercedes Benz");
if (s_mb && strcmp(s_mb->title, "Janis Joplin") == 0)
printf("Q4-5 ok\n");
else
printf("Q4-5 ERROR, Mercedes Benz not found correctly,
return = %d\n", tmp);
if (s_mb)
free(s_mb);
song *s_ds = find_song("songs.db", "Money for Nothing");
if (s_ds == NULL)
printf("Q4-6 ok\n");
else
printf("Q4-6 ERROR, found \"Money for Nothing\"\n");
if (s_ds)
free(s_ds);
return 0;
}
}