c - fscanf() 不读取和崩溃

标签 c file csv io scanf

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

  1. 计算文件中的字符数
  2. 分配一个足够大的 char * 来容纳所有的字符
  3. 使用 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() 调用对我来说似乎是正确的,但它会立即导致崩溃。我尝试打印索引以查看它是否已更改,但未打印出来。

欢迎任何形式的帮助。

最佳答案

您需要指向 fscanf 中的整数/ float 的指针,即

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

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

关于c - fscanf() 不读取和崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34684076/

相关文章:

python - 求和一列值,包括 Python 中的字母

c++ - 在 C/C++ 中获取文件大小的可移植方法

C、对结构队列进行排序

c - 打印浮点值时的奇怪行为

java - 创建一个包含增量值的新文件

java - 如何从我的电脑打开和查看文件夹?

c - "context"这个词在结构中通常是什么意思?

java - 在java中解析XML的访问权限

php - 使用php将csv上传到数据库表

Android:CSV 数据库与 SQLite 数据库