c - Reading in data from a file, using fscanf (following a sepecific pattern) -



c - Reading in data from a file, using fscanf (following a sepecific pattern) -

i trying read in file, , can't pattern of right. can tell me can working?

int main() { char name[20]; int age; float highbp, lowbp, risk; file *fp; fp = fopen("data.dat", "r"); if(fp == null){ printf("cannot open file\n\n"); } while(fscanf(fp, "name:%s\nage:%d\nbp:%f\nrisk:%f", name, &age, &highbp, &risk) != eof){ } printf("name: %s\n", name); printf("%d\n", age); printf("%f\n", highbp); printf("%f\n", risk); }

data.dat:

name:tom age:32 bp:43.00 risk:0.0

if can't open file prints message, continues. instead should homecoming main.

if (fp == null) { printf("cannot open file\n\n"); homecoming 1; }

fscanf homecoming number of items parsed, it's safer stop reading when number returned < 4 (not items read).

presumably "data.dat" contains multiple records , each line has line ending. means after reading first record next character in file line ending "risk:0.0" line. should end fscanf template \n.

this because sec time tries parse file, fscanf see character, isn't expecting (the fscanf template starts "name:"), stop reading, , you'll first record.

c

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -