lundi 18 avril 2016

Reading data from a file into a structure array (C)

I'm trying to build a simple function that will take in a data file, and assign various values from the data file into a global array of structures. However, I'm having trouble getting it to work quite right. I've written what I believe is most of the needed code, but my test line printf("time is %d\n", BP[i].time); simply reads out "Time is 0." 10 times, leading me to believe the values aren't getting assigned to the structure array like I imagined they would be.

How can I proceed further?

Example Data File (.txt):

0001    553    200
0002    552    100
....    ...   ...

Current Code:

#include <stdio.h>
#include <stdlib.h>

// Function Prototype
void readFileBP(char fileName[1000]);

// Definition of BP Structure
struct bloodPressure
{
    int *time;
    int *sys;
    int *dia;
}BP[50]; // end struct BP

int main()
{
    char fileName[1000] = "C:\\Users\\User\\Desktop\\DataFiles\\BP_1.txt";
    readFileBP(fileName);

    int i = 0;

    for (i; i<10; i++)
    {
        printf("Time is %d\n", BP[i].time);
    }
} // end int main()

void readFileBP(char fileName[1000])
{
    FILE *filePtr; // declare file pointer
    int time;
    int sys;
    int dia;
    int position = 0;


    if (filePtr = fopen(fileName, "r") == NULL) // error check opening file
    {
        printf("Opening file failed. Please reenter filename.");
        exit(1); 
    } // end if

    while (fscanf(filePtr, "%d, %d, %d", &time, &sys, &dia) != EOF) // read in BP values
    {
        BP[position].time = time;
        BP[position].sys = sys;
        BP[position].dia = dia;
        position++;

    } // end while

    fclose(filePtr);



} // end void readFile()

Aucun commentaire:

Enregistrer un commentaire