smooth_smoothie
smooth_smoothie

Reputation: 1343

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

I am trying to read in from a file, and I can't get the pattern of it right. Can someone tell me what I can do to get it 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

Upvotes: 1

Views: 2525

Answers (3)

che
che

Reputation: 12263

You should change the "name" format specifier from %s to %19s to make it read at most 19 characters (+terminating '\0'). The way you have it now is a guaranteed failure in case someone gives you 20+ character name.

Upvotes: 1

MRAB
MRAB

Reputation: 20654

If it can't open the file it prints a message, but then continues. Instead it should return from main.

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

fscanf will return the number of items parsed, so it's probably safer to stop reading when the number returned < 4 (not all the items could be read).

Presumably "data.dat" contains multiple records and each line has a line ending. This means that after reading the first record the next character in the file is the line ending for the "risk:0.0" line. You should end the fscanf template with \n.

This is because the second time it tries to parse the file, fscanf will see that character, which it isn't expecting (the fscanf template starts "name:"), so it will stop reading, and you'll get only the first record.

Upvotes: 1

pmg
pmg

Reputation: 108988

Can someone tell me what I can do to get it working?

I suggest you separate the functionality in different statements.
Don't try to cram all of the program functionality in 1 statement.

Your big statement is doing 3 things:

  • it is reading data from file
  • it is comparing the return value of scanf with EOF
  • it is controlling when to stop reading

I suggest you do (at least) 3 different statements for the 3 different actions.

Hint: comparing the return value of scanf only with EOF is a little too short

Upvotes: -1

Related Questions