使用strtok()获取特定字段

时间:2015-04-06 22:20:01

标签: c pointers dynamic-programming

我目前正在阅读C中的文件,其中包含格式为

的歌曲列表
Track ID<SEP>Song ID<SEP>Artist Name<SEP>Song Title

我很难理解如何使用strtok()<SEP>之后使歌曲艺术家和歌曲名称

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

如果我了解您正在阅读文件中的每一行,然后将其标记为检索歌曲,艺术家和标题,请在strtok循环中调用for,同时保留field index会做你需要的:

#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++;
    }
}

根据需要调整MAXSMAXL。 (退出更改字段的#和顺序:)

注意: <sep>是一个通用占位符,必须替换为strtok有效分隔符字符串

答案 1 :(得分:1)

将线路放入缓冲区后

...

char *TrackId = strtok( buffer, "<sep>" );
if( NULL != TrackId )
{
    char *SongID = strtok( NULL, "<sep>: );
    if( NULL != SongID )
    {
        char *ArtistName = strtok( NULL, "<sep>" );
        if( NULL != ArtistName )
        {
            char *SongTitle = strtok( NULL, "<sep>" );
            if( NULL != SongTitle )
            { // then have extracted all fields from line
                // process those fields
            }
         }
     }
  }