Skip to content
Advertisement

Scanning numbers from a file in C

I tried to scan some coordinates [X, Y, Z] from a file, but always returned as segmentation fault. So, I’ve some questions to make:

  1. I don’t know how many points are in the file, but if I leave the struct arrays empty, there will be an error. There is a way to do this without defining a max number?

  2. Are my use of pointers ok? I’m not very talented with them.

I think that what is causing the segmentation fault is the fscanf, but I can’t fix it

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define MAX 20000

FILE *f1;

struct points{
  int       n;
  float x[MAX];
  float y[MAX];
  float z[MAX];
};

int main (){

  int i;
  struct points cart1[MAX];
  f1 = fopen("point_cloud1.txt", "r");
  if (f1 == NULL){
    printf("Error Reading Filen");
    exit (0);
  }
  for(i = 0; !feof(f1); i++){
    fscanf(f1, "%f%f%f", &cart1[i].x[i], &cart1[i].y[i], &cart1[i].z[i]);
  }
  (*cart1).n = i+1;
  printf("nNumber: %d coord1: %f, %f, %fn", (*cart1).n, (*cart1).x[0], (*cart1).y[0], (*cart1).z[0]);

  fclose(f1);

return 0;
}

The beginning of the file is like this:

2.84838 -1.21024 -0.829256
7.09443 -3.01579 0.134558
3.31221 -1.40868 -0.830969
7.09813 -3.01883 0.404243
4.05924 -1.72723 -0.857496

Advertisement

Answer

You have a very large array declared as a local variable:

struct points cart1[MAX];

There are 20000 element in the array, and each array element is (assuming int and float each take up 4 bytes) 4 + 4 * 20000 + 4 * 20000 + 4 * 20000 = 240004 bytes for a total size of 4,800,080,000 ( 4.8 GB ). Even as a global variable, that’s huge. As a local, which on most implementations lives on the stack, this easily exceeds stack size which results in the core dump.

You don’t need an array of these structures, only a single one. Then you use it like this:

int main (){

  int i, r;
  struct points cart1;
  f1 = fopen("point_cloud1.txt", "r");
  if (f1 == NULL){
    printf("Error Reading Filen");
    exit (0);
  }
  for(i = 0, r = 3; r == 3; i++){
    r = fscanf(f1, "%f%f%f", &cart1.x[i], &cart1.y[i], &cart1.z[i]);
  }
  cart1.n = i+1;
  printf("nNumber: %d coord1: %f, %f, %fn", cart1.n, cart1.x[0], cart1.y[0], cart1.z[0]);

  fclose(f1);

return 0;
}

Also, don’t use feof

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement