1

I have to complete this exercise: I have to read from a generic text file, thus composed: [Nameperson][space][age],and i have to save the name(char) and the age(unsigned int) in a struct.

My problem is: I don't understand how to divide the name and age, that is, if I use a fread_s, in this way

fread_s(pp->name, 256, 1, 256, f);

the program saves me as name es.

Pippo 25iiiiiiiiiiiiiiiiiiiiiiiiii...

I know that the fread_s function maintain the position of the last letter read, but I do not know how to use this to my advantage . This is my code

#include <stdio.h>
#include <string.h>

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

void person_read(FILE *f, struct person* pp) {
    fread_s(pp->name, 256, 1, 256, f);
}

Thanks.

Amarildo
  • 268
  • 4
  • 19

1 Answers1

1

You are using the wrong function, you need fscanf()

int
person_read(FILE *file, struct person *person)
{
    // Warning: if names contain spaces "%255s%d" will not work
    if (fscanf(file, "%255s%d", person->name, person->age) != 2)
    {
        fprintf(stderr, "warning: invalid read!\n");
        return -1;
    }
    return 0;
}

Use it like this

struct person person;
if (person_read(file, &person) != 0)
    do_somethin_read_error();
else
    fprintf(stderr, "%s has %d years\n", person.name, person.age);

The reason your code is producing that output is because you are reading all the bytes from the file (or just 256) into person->name and since person->name is not null terminated, passing it to printf() produces the output you see and is *Undefined Behavior**.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • About fscanf Visual Studio said 'This function or variable may be unsafe. Consider using fscanf_s instead.' how can i solve it? – Amarildo Feb 04 '16 at 20:49
  • 2
    And that's why I don't like Visual Studio for students because it tries to force non standard functions. I knew it would say that, but I don't write code for MS Operating system so I can't help you with that sorry. I think if you add `#define _CRT_SECURE_NO_WARNINGS` in the very beginning of your file [it should silence the warnings and you would be able to use **standard** functions](http://stackoverflow.com/questions/16883037/remove-secure-warnings-crt-secure-no-warnings-from-projects-by-default-in-vis). – Iharob Al Asimi Feb 04 '16 at 20:49
  • You solve it as you "*Consider using `fscanf_s` instead.*" (instead of `fscanf`) – David C. Rankin Feb 04 '16 at 20:50