Reading Numbers from a .dat file with numbers arranged columnwise into an array in C

528 views Asked by At
#include<stdio.h>
#include<stdlib.h>

int main()
{
     int block[100];
     int i = 0;

     FILE *fp;

     fp = fopen("blockage.dat","r");

     if (fp != NULL){
     while( !feof(fp) )
     {
         fscanf(fp,"%d",&block[i++]);
     }
     }
     fclose(fp);

     return 0;

}

My blockage.dat file looks like this:

3.712e+05
4.265e+05
5.345e+05
....

The numbers are arranged row wise. So my C program is stuck in the first loop itself. How do I sort this ? How do I ensure that it goes to the next line ?

2

There are 2 answers

1
Gopi On BEST ANSWER

Where is i declared in your program?

Set i to 0.

int i = 0;

The file contains floating type data. So your array should be

float block[100];

Then do

while((fscanf(fp,"%f",&block[i++])) != EOF);

Depending on the values which you are reading you declare your array with double or long double type.

2
Scott Hunter On

The problem has nothing to do with arrangement; you are trying to read floats into integer variables.