1

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.

1
  • Doyou have maximum number of columns per line? Commented May 29, 2010 at 11:25

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Very neat solution, Thank you so much. Now, I have another question in this regard, which is reading the second number in each line of the file and place them into an array of type float. What function do I need to use in order to achieve that. Any input would help greatly
The simplest solution is to store at the very beginning of your file the number of floats you will need to store. You can always know this number. Right after reading the first line, do a float* f = (float*)calloc(nb_floats, sizeof(float)); store your values in here, and return the pointer.
Thank you once again for your input; my problem actually is how to return the float numbers stored in the file then placing them into an array. i.e. my file is 14 12.57 3 9.54 35 11.25 67 45.12 95 33.17 I want to extract from the file only the float values then place them in array so that my Read(FILE* pFile) function would return an Array[]=12.57, 9.54, 11.25, 45.12, 33.17. Many thanks in advance.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.