【发布时间】:2016-04-13 13:13:15
【问题描述】:
我目前正在尝试解析 .csv 文件并将字段提取到 C 中的一些动态分配的数组中。 我尝试通过以下方式解析文件:
- 统计文件中的字符数
- 分配一个足够大的字符 * 以容纳所有字符
- 使用 strtok 对输入进行标记,以便将其存储在数组中
但是,这种方法并不成功,因为 .csv 包含 10^10 个字符,而我的计算机内存不足(低于 2 GB)。
但是,由于文件仅包含 10^5 行,我尝试了另一种方法:我打开 .csv 文件并逐个标记读取它,删除逗号 (,) 并在需要的地方放置空格。之后,我得到了一个新的文本文件,每行有 4 个字段:
Integer Double Double Double
Id Latitude Longitude Weight
我目前正在尝试使用 fscanf 从该文件中逐行读取,然后将读取的值存储到使用 malloc 分配的 4 个数组中。代码在这里:
int main()
{
const int m = 100000;
FILE * gift_file = fopen("archivo.txt", "r");
if( gift_file != NULL) fprintf(stdout, "File opened!\n");
create_saving_list(m , gift_file);
return 0;
}
void create_saving_list( int m, FILE * in )
{
unsigned int index = 0;
double * latitude = (double *)malloc(m*sizeof(double));
if( latitude == NULL ) fprintf(stdout, "Not enoug memory - Latitude");
double * longitude = (double *)malloc(m*sizeof(double));
if( longitude == NULL ) fprintf(stdout, "Not enoug memory - Longitude");
double * weight = (double *)malloc(m*sizeof(double));
if( weight == NULL ) fprintf(stdout, "Not enoug memory - Weight");
int * id = (int *)malloc(m*sizeof(int));
if( id == NULL ) fprintf(stdout, "Not enough memory - ID");
while( fscanf( in, "%d %lf %lf %lf\n", id[index], latitude[index], longitude[index], weight[index] ) > 1 )
{
index += 1;
}
/* Processing of the vector ...*/
}
我已经能够跟踪内存分配并验证它们是否正确执行。问题出在 while() 内部,因为 fscanf() 调用对我来说似乎是正确的,但它会立即导致崩溃。我尝试打印索引以查看它是否已更改,但未打印。
欢迎任何形式的帮助。
【问题讨论】: