Home > Mobile >  how to read data from a file in this exercise?
how to read data from a file in this exercise?

Time:05-07

I have to do this exercise:

short explanation:

read a file, and store informations in a struct pointed to by a pointer.

long explanation:

I have a struct "person", and it contains: char name[256]; unsigned int age.

struct person {
    char name[256];
    unsigned int age;
};

I have to implement this function:

void person_read (FILE *f, struct person *pp);

I have to read informations with this formatting style:

<person's name> <whitespace> <age> 
<person's name> <whitespace> <age> 
<person's name> <whitespace> <age> 
<person's name> <whitespace> <age> 

and store each data in the struct pointed to by this pointer.

the problem is that I have no idea how to read person's name, skip whitespace and then read age. How can I set up a reading function like this: 1) read person's name, 2) skip whitespace, 3) read age ?

fgetc() function is not a solution, because it reads only 1 character, and a person's name doesn't have 1 single character. on the other hand, fscanf() function reads everything.

my idea is to use 1) read, 2) check, 3) use

  1. read a char, check if it's not a whitespace, if it's true, then store in the array name of the struct. (if it's true, that means that in the array I have full person's name).
  2. read again, and again, and so on until a whitespace it's reached. Then skip the whitespace.
  3. read age, and store it in the struct (unsigned int age).

but I think I'm overcomplicating the job. is there a simpler way?

CodePudding user response:

The canonical solution is:

int r = fscanf(f, "%5s %u\n", p->name, &p->age);

where p your person pointer. You want to check that r is 2 in this case so you have a valid data for both fields.

  • Related