If I understand you are reading each line from a file, and then tokenizing them to retrieve the song, artist and title, calling strtok
in a for
loop while keeping a field index
will do what you need:
#define MAXS 128
#define MAXL 1024
...
char song[MAXS] = {0};
char artist[MAXS] = {0};
char title[MAXS] = {0};
char buf[MAXL] = {0};
...
while ((fgets (buf, 254, file)) != NULL)
{
char *p = buf;
fldidx = 0; /* field index */
for (p = strtok (buf, <sep>); p != NULL; p = strtok (NULL, <sep>))
{
if (fldidx == 1) strncpy (song, p, strlen (p)+1);
if (fldidx == 2) strncpy (artist, p, strlen (p)+1);
if (fldidx == 3) strncpy (title, p, strlen (p)+1);
fldidx++;
}
}
Adjust MAXS
, MAXL
as needed. (quit changing the # and order of fields :)
Note: <sep>
is a generic placeholder that must be replaced by a valid delimiter string for strtok
.