Last active
March 28, 2016 07:40
-
-
Save kazmura11/1fc47cc795f17c132224 to your computer and use it in GitHub Desktop.
ダブルクォートで囲まれたCSVの読込みテストプログラム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* reference | |
* http://f4.aaacafe.ne.jp/~pointc/log1227.html | |
* ・一行の中のデータは ,(カンマ)で区切る。行の終りは改行。 | |
* ・データがカンマやダブルクォートを含む場合は "(ダブルクォート)で囲む。 | |
* ・データの中のダブルクォートはそれをダブルクォート2個("")で置き換える。 | |
*/ | |
#include <stdio.h> | |
char *setvalue(char *p, char *field, int size) | |
{ | |
if (*p == '"') | |
{ | |
/* ここでのインクリメントは | |
* 最後のインクリメントではポインタが+2になる(評価された場合のみ) | |
* *p != '"'が0になった場合のみ *(++p) == '"'が実行される | |
* これはダブルクォート連続の時の対策 | |
*/ | |
while (*(++p) && *p != '\n' && (*p != '"' || *(++p) == '"')) | |
{ | |
if (--size > 0) | |
{ | |
*(field++) = *p; | |
} | |
} | |
} | |
// ここの部分は""で囲まれていない部分が通るようになっている | |
for ( ; *p && *p != ',' && *p != '\n'; p++) | |
{ | |
if (--size > 0) | |
{ | |
*(field++) = *p; | |
} | |
} | |
*field = '\0'; | |
return *p ? (p + 1) : p; | |
} | |
int main() | |
{ | |
char buf[256]; // 256にしているのは手抜き実装 | |
char field[256]; | |
char *p; | |
FILE *fp = NULL; | |
if ((fp = fopen("test.csv", "r")) == NULL) { return 1; } | |
while (fgets(buf, sizeof(buf), fp)) | |
{ | |
// カラムごとに:で区切って出力 | |
for (p = buf; *p; ) | |
{ | |
p = setvalue(p, field, sizeof(field)); | |
printf(":%s", field); | |
} | |
puts(""); | |
} | |
fclose(fp); | |
return 0; | |
} |
We can make this file beautiful and searchable if this error is corrected: Any value after quoted field isn't allowed in line 5.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"123","456","789" | |
"abcd","efg","hij" | |
"klm","nop","qrs" | |
"あいう","えお","かきく" | |
"12"3,"456","789" | |
"12""3","456","789" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
最初のコメントが大ウソだったので訂正