1

I'm making a program in C with structures. It must read some text from a text file and save it into a struct. When I print the struct, I see my information with some random numbers and characters after it. Can someone help me?

#include<stdio.h>

typedef struct {

    char naam[32];
    int telefoon;
} Persoon;

void drukadres(Persoon*);

int main(void)
{
    Persoon p;
    FILE *Bestand;

    Bestand = fopen("Bestand.txt", "r");

    while (fread(&p,sizeof(Persoon),1,Bestand)!=NULL)
    {
        drukadres(&p);
    }
}

void drukadres(Persoon *p)
{
    printf("%s %d", p->naam,p->telefoon);

}

This is in my text file:

Vincent 0473352787 
Janssens 56445343445

Thanks!

Manariba
  • 376
  • 6
  • 16
  • The record sizes in your text file are variable, yet you are reading them into a fixed-size struct. You are also not converting the string of digits `telefoon` to an integer before attempting to store it in the `Persoon` struct. Both of these will cause the behavior you are seeing? – Joel Cornett Jan 12 '15 at 15:37
  • What is the output? For starters you should not use sizof(Persoon) as this maximum possible but the naam is less that 32 chars. The naam is variable in length. – Pankaj Bansal Jan 12 '15 at 15:38
  • `fread` will not do text conversions for you. It just dumps binary data into your structure. You need to manually marshal the data into an appropriate structure. – fuz Jan 12 '15 at 15:45

1 Answers1

2

As your input file is text you must use text input function instead of the binary fread !

You could use something like :

int main(void)
{
    Persoon p;
    FILE *Bestand;
    char line[64];
    int num = 0;

    Bestand = fopen("Bestand.txt", "r");

    while (fgets(line, sizeof(line), Bestand)!=NULL)
    {
        num += 1;
        if (2 != sscanf("%31s %d", p.naam, &(p.telefoon))) {
            fprintf(stderr, "Error line %d\n", num);
            break;
        }
        drukadres(&p);
    }
}
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252