首页 文章

fscanf()没有阅读和崩溃

提问于
浏览
0

我目前正在尝试解析.csv文件并将字段提取到C中的一些dinamically分配的数组 . 我尝试通过以下方式解析文件:

  • 计算文件中的字符数

  • 分配一个足够大的字符来容纳所有字符

  • 使用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()调用对我来说似乎是正确的,但它会导致崩溃 . 我尝试打印索引以查看它已更改,但它没有打印 .

欢迎任何形式的帮助 .

3 回答

  • 1

    您需要指向 fscanf 中的整数/浮点数,即

    fscanf( in, "%d %lf %lf %lf\n", &id[index], &latitude[index], &longitude[index], &weight[index] ) == 4 )
    

    还要检查它是否等于4,因为您希望使用所有格式并为所有变量赋值

  • 3

    我想你应该在这里提供元素的地址:

    fscanf( in, "%d %lf %lf %lf\n", &id[index], &latitude[index], &longitude[index], &weight[index])
    

    它应该工作

  • 2
    fscanf( in, "%d %lf %lf %lf\n", id[index], latitude[index], longitude[index], weight[index] )
    

    应该

    fscanf( in, "%d %lf %lf %lf\n", &id[index], &latitude[index], &longitude[index], &weight[index] )
    

    您需要将变量的地址传递给fscanf

相关问题