【发布时间】:2019-07-25 10:09:42
【问题描述】:
我正在尝试读取一个巨大的 .csv 文件(大约 100,000 行)。使用 fgets,我提取了整行,然后使用 sscanf,我在该行中读取了 21 个 int 值。但是,sscanf 在第 758 行返回错误 EXC_BAD_ACCESS。我试图增加缓冲区的大小并且可以读取更多行但不是全部。有没有更优雅、更干净的方式来用 C 读取海量数据?谢谢。
char buffer[316]; // buffer to contain one line
int x[20][100000]; // int values saved in a matrix
int line = 0; // counter for lines
int j = 0; // counter for lines (excluding headers)
FILE *fp;
char fname[] = "/Users/basho/data_TS-20.csv";
fp = fopen(fname, "r");
if(fp == NULL) {
printf("%s file not open!\n", fname);
return -1;
}
// read one line at a time using fgets
while (fgets(buffer, sizeof buffer, fp) != NULL) {
if (line > 1) // we first skip the two first lines of the file, some empty line and the header.
{
printf("line %d\n",line);
sscanf(buffer, "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d, ",
&x[0][j], &x[1][j], &x[2][j], &x[3][j], &x[4][j], &x[5][j], &x[6][j], &x[7][j], &x[8][j], &x[9][j],
&x[10][j], &x[11][j], &x[12][j], &x[13][j],&x[14][j], &x[15][j], &x[16][j], &x[17][j], &x[18][j],
&x[19][j], &x[20][j]);
for(int i = 0; i<20; i++){
printf("%d ",x[i][j]);
}
printf("%d\n",x[20][j]);
j = j+ 1;
//}
}
line =line + 1;
}
fclose(fp);
return 0;
}
【问题讨论】:
-
x[20][100000](~8Mb 假设 32 位整数)对于局部变量来说可能太大了 -
当我第一次将整数加载到一些中间变量,然后将它们复制到表中时,它起作用了。谢谢。