NaNa21
NaNa21

Reputation: 11

Reading from a file into an array in c

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.

Upvotes: 1

Views: 1432

Answers (2)

wormsparty
wormsparty

Reputation: 2499

Use something like this. And if you want a reentrant code, see man strtok_r

#define MAX_BUFFER 200

float Read(FILE* pFile)
{
    char line[MAX_BUFFER];

    while(fgets(line, MAX_BUFFER, pFile) != NULL)
    {
        char* ptr = strtok(line, " ");

        while(ptr != NULL)
        {
            printf("2.5f ", (float)atof(ptr));
            ptr = strtok(NULL, " ");
        }

        printf("\n");
    }
}

Note that you wrote line[50] but read 200 in fgets(), that is, a potential buffer overflow. 'i' isn't even declared and pFile is never used.

Upvotes: 1

Daniel Goldberg
Daniel Goldberg

Reputation: 20518

Look up strtok and tokenizing.

Make sure you think about several things, such as figuring out the length of the array you need (memory management), keeping track of where in the array you are, etc.

Upvotes: 0

Related Questions