Reading from a file into an array in c

Posted by NaNa21 on Stack Overflow See other posts from Stack Overflow or by NaNa21
Published on 2010-05-29T11:22:08Z Indexed on 2010/05/29 11:32 UTC
Read the original article Hit count: 153

Filed under:

My file contains a series of numbers (integer, float, integer, float ....), each written on a separate line. The numbers of columns are different from one line to another i.e.

1 2.45 3 1.75

5 3.45 7 2.55 9 3.25

6 1.75 4 3.55 6 2.55 9 2.45

The program should read the contents of the entire file and place the data into an array of type float with an entry for each line. Here is my basic solution, but this is only suitable if I have fixed no of columns.

float Read(FILE *pFile)
{
 char line[50]; char letter[5];
 fi = fopen("file.txt", "r");

 while (fgets(line,200,fi)!=NULL)
 {

    sscanf(line,"%f %f %f",&a[i], &a2[i],&a3[i]);
     printf("%2.0f %2.5f %2.0f\n",a[i],a2[i],a3[i]);
}

fclose(fi);
return a[i];
}

Please HELP.

© Stack Overflow or respective owner

Related posts about c