Luciano
Luciano

Reputation: 543

Reading multiple numbers from a file into a struct in C

I have a small bit of code that should read values from a file with the following format:

0 0 0
0 0 2
0 2 0
0 2 2
2 0 0
2 0 2
2 2 0
2 2 2

into parts of a struct. I wrote a small program to confirm this was working, but when I print the result I get 0s for every term. I'm not sure what I'm doing wrong, so any help would be much appreciated. The test code is:

#include <stdio.H>
#include <stdlib.H>

            struct particle
            {
                double x[3];
            };

#define N 8 //number of particles

            struct particle particles[N];

            void starting_positions()
            {
                int p;
                FILE * startingpositions;//any .txt file
                startingpositions = fopen("startingpositions.txt", "r");
                for(p=0;p<N;p++)
                {
                    fscanf(startingpositions,"%lf %lf %lf\n", &particles[p].x[0],&particles[p].x[1],&particles[p].x[2]);
                }
                return;
            }

            int main()
            {
                int p;
                for(p=0;p<N;p++)
                {
                    printf("%lf %lf %lf\n", particles[p].x[0],particles[p].x[1],particles[p].x[2]);
                }
                return 0;
            }

Upvotes: 1

Views: 46

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

The problem here is, you never called starting_positions() in your main(). So, the file is never opened, never read and the elements in the particles array are never assigned any value.

So, the particles array elements, (particles being a global) are implicitly initialized to 0 and that's the value it prints.

Upvotes: 3

Related Questions