Im trying to add aa struct Song to my struct pointer song* but when trying to write it to a file it just gives out junk. This is my function:
void addSong(Song *song, char songName[], char artistName[], int publicationYear, int *nrOfSongs)
{
Song *tempSongs = (Song*)malloc(sizeof(Song)*(*nrOfSongs));
for (int i = 0; i < (*nrOfSongs); i++)
{
strcpy(tempSongs[i].artistName, song[i].artistName);
strcpy(tempSongs[i].songName, song[i].songName);
tempSongs[i].publicationYear = song[i].publicationYear;
}
free(song);
*nrOfSongs = (*nrOfSongs) + 1;
song = (Song*)malloc(sizeof(Song)*(*nrOfSongs));
for (int i = 0; i < ((*nrOfSongs)-1); i++)
{
strcpy(song[i].artistName, tempSongs[i].artistName);
strcpy(song[i].songName, tempSongs[i].songName);
song[i].publicationYear = tempSongs[i].publicationYear;
}
}
Edit 1: Sorry for the bad question.
My function writeToFile:
void writeToFile(char fileName[], Song *song, int *nrOfSongs)
{
char name[256];
snprintf(name, sizeof(name), "%s.txt", fileName);
FILE * file = fopen(name, "w");
fprintf(file, "%d", *nrOfSongs);
fputc('\n', file);
for (int i = 0; i < (*nrOfSongs); i++)
{
fputs(song[i].songName, file);
fputs(song[i].artistName, file);
fprintf(file, "%d", song[i].publicationYear);
fputc('\n', file);
}
fclose(file);
}
An example of a file:
4
Mr Tambourine Man
Bob Dylan
1965
Dead Ringer for Love
Meat Loaf
1981
Euphoria
Loreen
2012
Love Me Now
John Legend
2016
I want to add a song and by that i want to add an artistName, songName and publicationYear to my struct pointer and then write the struct pointer to a new file.
Instead of copying over arrays twice, you should enlarge the array song
using realloc()
, and just add the new element to it, like so:
Song *addSong(Song *song, char songName[], char artistName[], int publicationYear, int *nrOfSongs) {
*nrOfSongs++;
song = realloc(song, *nrOfSongs * sizeof *song);
// Don't forget to do error checking here, realloc() may return NULL
strcpy(song[*nrOfSongs - 1].artistName, artistName);
// et cetera
return song;
}
Because you are reallocating the memory, the pointer to the array changes, so you have to return the new pointer to the caller, like @wildplasser says.
Also, strcpy()
is an unsafe function. Consider using a safer alternative, like snprintf()
.
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.