fscanf() only reading in one record, and ignoring the rest
I am reading in records, using fscanf and using a while condition to test that it's reading in expected number of inputs. However, It stops reading in new records after it has read the first one. I can't seeem to put my finger on it.
#include <stdio.h>
#include <stdlib.h>
//STRUCTURE
typedef struct{
char name[20];
int age;
float highBP;
float lowBP;
float riskFactor;
} patient;
patient *pRecords[29];
int counter = 0;
int main(int argc, char **argv)
{
int i=0;
for(;i<30;i++){
pRecords[i] = (patient *)malloc(sizeof(patient));
}
FILE *fp;
fp = fopen("data.dat", "r");
if(fp == NULL){
printf("cannot open file\n\n");
return 1;
}
while(fscanf(fp, "name:\t%s\nage:\t%d\nbp:\t%f %f\nrisk:\t%f\n\n", pRecords[counter]->name, &pRecords[counter]->age, &pRecords[counter]->highBP, &pRecords[counter]->lowBP, &pRecords[counter]->riskFactor) == 5){
//printf("%d\n",fscanf(fp, "name:\t%s\nage:\t%d\nbp:\t%f %f\nrisk:\t%f\n\n", pRecords[counter]->name, &pRecords[counter]->age, &pRecords[counter]->highBP, &pRecords[counter]->lowBP, &pRecords[counter]->riskFactor));
printf("%s\n", pRecords[counter]->name);
printf("%d\n", pRecords[counter]->age);
printf("%f\n", pRecords[counter]->highBP);
printf("%f\n", pRecords[counte开发者_如何学JAVAr]->lowBP);
printf("%f\n", pRecords[counter]->riskFactor);
counter++;
}
}
data.dat
name: hank
age: 32
bp: 32.00 32.00
risk: 0.0
name: tom
age: 21
bp: 121.00 81.00
risk: 2.0
name: cindy
age: 32
bp: 190.00 900.00
risk: 5.0
You define an array with space for 29 elements
patient *pRecords[29];
and then proceed with assigning values to 30 elements.
for(;i<30;i++){
pRecords[i] = (patient *)malloc(sizeof(patient));
}
Don't do that! Anything can happen, including the behaviour you describe.
Also, don't cast the return value of malloc()
. It is redundant at best and may hide an error the compiler would have caught in the absence of the spurious cast.
I like to use information the compiler already knows for loops and malloc and stuff
patient *pRecords[29];
for (size_t i = 0; i < sizeof pRecords / sizeof *pRecords; i++) { /* 1 */
pRecords[i] = malloc(sizeof **pRecords); /* 2 */
}
- line /* 1 */:
sizeof pRecords / sizeof *pRecords
is the number of elements (pointers) in the array - line /* 2 */:
sizeof **pRecords
is the size of each (dereferenced) element
精彩评论