I'm learning C and trying to write a program to hold music information. I'm reading from a file with the following contents:
Hello,Adele,2015
Sorry,Justin Bieber,2015
X Gon Give It To Ya,DMX,2002
And trying to do a fairly basic operation - look at each line until EOF, grab the content, tokenize using ',' as delimiter, store each part of the string into 3 variables, store those 3 variables into the global array using the global index, which is defined in main like this
Song SongList[1024];
int globalCounter;
globalCounter = 0;
The function I wrote looks like this, where fp is a successfully opened file, SongList is an array of Song structures and globalCounter is the global index of current position in array.
int getFileData(FILE *fp, Song *SongList, int globalCounter) {
int newCount = globalCounter;
char fileOut[1024];
int lineno = 0;
while (!feof(fp)) {
if (fgets(fileOut, 1024, fp) != NULL) {
newCount++;
char *tokenizer;
char *fileTitle;
char *fileArtist;
char *fileYear;
tokenizer = strtok(fileOut, ",");
int counter = 0;
fileTitle = tokenizer;
counter++;
while (tokenizer != NULL) {
tokenizer = strtok(NULL, ",");
if (counter == 1)
fileArtist = tokenizer;
if (counter == 2)
fileYear = tokenizer;
counter++;
}
SongList[newCount].title = fileTitle;
SongList[newCount].artist = fileArtist;
SongList[newCount].year = fileYear;
// prints the right values
printf("%i\n", newCount);
printf("TITLE: %s\n", SongList[newCount].title);
printf("ARTIST: %s\n", SongList[newCount].artist);
printf("YEAR: %s\n", SongList[newCount].year);
}
}
return newCount;
}
It looks like it works fine, however, when I try to do a simple print of contents before the return statement, I get garbage return data.
int counter = 0;
while (counter < newCount) {
printf("%s, %s, %s", SongList[newCount].title, SongList[newCount].artist, SongList[newCount].year);
counter++;
}
yields:
X Gon Give It To Ya, DMX, 2002X Gon Give It To Ya, DMX, 2002X Gon Give It To Ya, DMX, 2002
When I try to use pretty much the exact same while loop in another function, I get even more garbage data output.
(null), (null), (null), , ╨╦a, , DMXm
The song structure looks like this
typedef struct Song {
char *title;
char *artist;
char *year;
} Song;
I suspect the problem has a simple solution: something to do with type definitions of variables, missing */&, or not ending with '\0' - I'm not sure what is causing this though.
Songitems has to have it's fields allocated. And to reduce the chance of being downvoted - remove justin Bieber from your list :)newcountwhere I believe you should be usingcounter(otherwise you're just printing the same song several times).