Hi All,
i'm pretty new to C programming.
In the following i will put the first program i wrote.
If i try to open a file named "bruco.coord" containing a few lines with number the code works fine.
If i try to open named "bruco.coord" containing 81Milions of lines the code gives me the error "segmentation fault".
In both cases structure of bruco.coord is something like
1 4
2 5
5 8
and so on...
Here is my code, any idea on how to solve the problem ?
Thanks,
Andrea
Code:
#include <stdio.h>
#include <string.h>
int main ( void )
{
char filename[] = "bruco.coord";
FILE *file ;
file= fopen (filename,"r");
if ( file != NULL )
{
char line [8260000]; /* or other suitable maximum line size */
float step=-0.4;
int i;
float min=-0.02;
float max=0.02;
float a[10000];
float limit1;
float limit2;
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
sscanf(line,"%f%f", &limit1, &limit2);
if (limit2==11111111)
{
int indice0=0;
float maxval=0;
float minval=0;
for (indice0 = 0 ; indice0 < i ; indice0++)
{
if (a[indice0] > maxval)
{
maxval = a[indice0] ;
}
}
for (indice0 = 0 ; indice0 < i ; indice0++)
{
if (a[indice0] < minval)
{
minval = a[indice0];
}
}
int passo=0;
float bin_center[10000];
int indice2=0;
int freq_count[10000];
float freqsize=1000;
float bin_size=(maxval - minval)/freqsize;
for (passo=0; passo<freqsize; passo++)
{
for (indice2 = 0; indice2 < i ; indice2++)
{
if ((a[indice2]>minval+passo*bin_size)&(a[indice2]<minval+(passo+1)*bin_size))
{
freq_count[passo]++;
bin_center[passo]=minval+passo*bin_size;
}
else if ((a[indice2]<minval+passo*bin_size))
{
bin_center[passo]=minval+passo*bin_size;
}
else if ((a[indice2]>minval+(passo+1)*bin_size))
{
bin_center[passo]=minval+passo*bin_size;
}
}
}
int ciao=0;
for (ciao=0; ciao<freqsize; ciao++)
{
printf("%f %f %i\n",step, (bin_center[ciao]*57.32-step), freq_count[ciao]);
FILE *destinazione;
destinazione = fopen("file.txt","a+"); /* apend file (add text to a file or create a file if it does not exist.*/
fprintf(destinazione,"%f %f %i\n",step, (bin_center[ciao]*57.32-step), freq_count[ciao]); /*writes*/
fclose(destinazione); /*done!*/
}
memset(a, 0, i);
memset(freq_count, 0, i);
memset(bin_center, 0, i);
i=0;
step=step+0.01;
}
/* conto il numero di elementi che mi interessa binnare */
else if ((limit2<max)&(limit2>min))
{
a[i] = limit2;
i++;
}
/* fine del conteggio */
}
fclose ( file );
}
else
{
perror ( filename ); /* why didn't the file open? */
}
return 0;
}