トークン毎のデータ抜き出し

エクセル等の出力では良くCSVと言うカンマ(,)区切りのデータフォーマットが用いられますが、それら区切り文字で分けられた各データをトークンと呼びます。区切り文字を適当に指定すればCSV形式のファイルをスペース区切りのフォーマットにしたり、その逆等も可能です。

トークン毎のデータ抜き出し例題(list_18.c)
#include <stdio.h>

int main(int argc,char* argv[])
{
    FILE *fp;
    int i,cnt,score;
    char fbuf[255];
    char seps[]=",",*token;

    if(argc < 2){
        fprintf(stderr,"usage:%s inputfile\n",argv[0]);
        exit(-1);
    } else {
        printf("fname = %s\n",argv[1]);
        fp = fopen(argv[1],"r");
    }
    
    while(fgets(fbuf,255,fp)){
        token = strtok( fbuf, seps );
        cnt = 0;
        while( token != NULL ){ /* buf にトークンがなくなるまで繰り返す */
            sscanf(token,"%d",&score);
            printf("%d ",score);
            /* 次のトークンを取得 */
            token = strtok( NULL, seps );
            cnt ++;
        }
        printf("\n");
    }

    fclose(fp);
}
実行結果
Gami[986]% cat token.txt
1,19,29
2,13,45
3,43,23
442,36,51
443,25,11

Gami[987]% list_18.exe token.txt
fname = token.txt
1 19 29
2 13 45
3 43 23
442 36 51
443 25 11
Gami[988]%
inserted by FC2 system