回答編集履歴
1
strtol を使うコードを追加
test
CHANGED
@@ -5,3 +5,95 @@
|
|
5
5
|
|
6
6
|
|
7
7
|
fscanf の書式を "%d," に変更するだけではダメでしょう。
|
8
|
+
|
9
|
+
|
10
|
+
|
11
|
+
**追記**
|
12
|
+
|
13
|
+
fgets と strtol を使った例です。他にもやり方はあります。
|
14
|
+
|
15
|
+
```C
|
16
|
+
|
17
|
+
#include <stdio.h> // fopen, fclose, fgets, puts, printf, putchar
|
18
|
+
|
19
|
+
#include <stdlib.h> // strtol
|
20
|
+
|
21
|
+
|
22
|
+
|
23
|
+
#define BUF_SIZE 256
|
24
|
+
|
25
|
+
#define LINE_SIZE 20
|
26
|
+
|
27
|
+
#define FIELD_SIZE 16
|
28
|
+
|
29
|
+
|
30
|
+
|
31
|
+
int main(void)
|
32
|
+
|
33
|
+
{
|
34
|
+
|
35
|
+
FILE *fp = fopen("Book1.csv", "r");
|
36
|
+
|
37
|
+
if (fp == NULL) return 1;
|
38
|
+
|
39
|
+
|
40
|
+
|
41
|
+
char buf[BUF_SIZE];
|
42
|
+
|
43
|
+
int line;
|
44
|
+
|
45
|
+
for (line = 0; fgets(buf, BUF_SIZE, fp); line++) ;
|
46
|
+
|
47
|
+
if (line > LINE_SIZE) { puts("too many lines"); return 2; }
|
48
|
+
|
49
|
+
|
50
|
+
|
51
|
+
rewind(fp);
|
52
|
+
|
53
|
+
|
54
|
+
|
55
|
+
int data[LINE_SIZE][FIELD_SIZE], count[LINE_SIZE];
|
56
|
+
|
57
|
+
for (int i = 0; fgets(buf, BUF_SIZE, fp); i++) {
|
58
|
+
|
59
|
+
char *p = buf, *sep;
|
60
|
+
|
61
|
+
int j = 0;
|
62
|
+
|
63
|
+
while (j < FIELD_SIZE) {
|
64
|
+
|
65
|
+
data[i][j] = strtol(p, &sep, 10);
|
66
|
+
|
67
|
+
if (sep == p) break;
|
68
|
+
|
69
|
+
if (++j >= FIELD_SIZE) { puts("too many fields"); return 3; }
|
70
|
+
|
71
|
+
if (*sep != ',') break;
|
72
|
+
|
73
|
+
p = sep + 1;
|
74
|
+
|
75
|
+
}
|
76
|
+
|
77
|
+
count[i] = j;
|
78
|
+
|
79
|
+
}
|
80
|
+
|
81
|
+
fclose(fp);
|
82
|
+
|
83
|
+
|
84
|
+
|
85
|
+
for (int i = 0; i < line; i++) {
|
86
|
+
|
87
|
+
for (int j = 0; j < count[i]; j++)
|
88
|
+
|
89
|
+
printf("%10d", data[i][j]);
|
90
|
+
|
91
|
+
putchar('\n');
|
92
|
+
|
93
|
+
}
|
94
|
+
|
95
|
+
return 0;
|
96
|
+
|
97
|
+
}
|
98
|
+
|
99
|
+
```
|