我正在尝试从一个巨大的.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;
}
答案 0 :(得分:3)
查看int x[20][100000];
和&x[20][j]
->按1关闭。
// int x[20][100000];
int x[21][100000];
也
j = j+ 1;
if (j >= 100000) break;