22
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CのfscanfによるCSV(カンマで区切られたファイル)の読み込みメモ

Last updated at Posted at 2015-12-15

初心者によるメモ

fscanfにおいて,%sは空白文字(スペース,改行,タブ,改ページ…)で自動的に区切られる.
カンマは文字列の一部として読み込んでしまうので,カンマで区切られた文字列を読みこむときには%[^,]を用いる.

fscanf(fp, "%[^,],&[^,],%s", buf1, buf2, buf3);

(行末はカンマでなく改行で区切られる点に注意)

sample.csv
label1,label2,label3
0.1,1.5,1.7
0.2,1.7,2
0.3,2.1,2.6
read_sample.c

#include <stdio.h>

int main(){
  FILE *fp;
  char *fname = "sample.csv";
  int ret;
  char buf[3][10];
  double data[3];

  fp = fopen( fname, "r" );
  if( fp == NULL ){
    printf( "%sファイルが開けません\n", fname );
    return -1;
  }
    
  printf("\n");
  
  fscanf(fp, "%[^,],%[^,],%s", buf[0], buf[1], buf[2]);
  printf("%s %s %s\n",buf[0], buf[1], buf[2]);


  while( (ret=fscanf(fp, "%lf,%lf,%lf", &data[0], &data[1], &data[2])) != EOF){
    printf("%lf %lf %lf\n", data[0], data[1], data[2]);
  }

  printf("\n");
  fclose( fp );
}

出力結果
label1 label2 label3
0.100000 1.500000 1.700000
0.200000 1.700000 2.000000
0.300000 2.100000 2.600000
22
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?