0

I have the following code:

typedef struct my_data {
 char* name;
}my_data;

my_data data[]={
    { .name = "Peter" },
    { .name = "James" },
    { .name = "John" },
    { .name = "Mike" }
};


void loaddata()
{
    FILE * in;
    if((in = fopen("data.txt","rt")) != NULL) {
        printf("start loading\n");
        int i = 0;
        while(!feof(in))
        {
            fscanf(in,"%s", &data[i].name);
            printf("%s\n",data[i].name);
            i++;
        };
    }
    else
        printf("loading not required\n");
    fclose(in);
}

And it gives me a "killed" error.

How can I load data from file data.txt into existing structure and in case file doesn't exist to use default values which were defined ?

Sam Reina
  • 305
  • 1
  • 7
  • 22

1 Answers1

1

No need "&" in:

fscanf(in,"%s", &data[i].name);

and no need to close filestream if it's not opened.

void loaddata()
{
    FILE * in;
    if((in = fopen("data.txt","rt")) != NULL) {
        printf("start loading\n");
        int i = 0;
        while(!feof(in))
        {
            fscanf(in,"%s", data[i].name);
            printf("%s\n",data[i].name);
            i++;
        };
        fclose(in); /* need closing */
    }
    else
        printf("loading not required\n");
    /* no need closing */
}

UPD: create structure with allocated memory, not pointer. Pointer accesses part of program, not memory, so you cannot save data there.

typedef struct my_data {
    char name[10];
}my_data;
Oleg Olivson
  • 489
  • 2
  • 5