Search code examples
cfile-iostructdynamic-memory-allocation

reading from txt file into dynamicly allocated


I want to read some data from txt file and store it in s_person struct and than print it latter. Text file structure looks like this:

john 43 23
steven 23 44
micheal 11 0

Variable array is for those 2 numbers next to name in txt file.

#include<stdio.h>
#include<stdlib.h>

struct s_person {
    char *name;
    int *array;
};

Here I have constructor that constructs number of s_person that you want to read from a file.

s_person* construct(int number){    
    s_person *person = (s_person*)malloc(sizeof(s_person) * number);
    if(person){
        person->name = (char*)malloc(sizeof(char) * 50);
        person->array = (int*)malloc(sizeof(int) * 2);
    }
    return person;
}

Here is the function that reads data from txt file. It seems to break at second run through while loop at fscanf(f,"%s", osoba[i].name); if I have to read more than one row.

 void getData(s_person *person, int number) {
        FILE *f = fopen("text.txt", "r");
        if(f == NULL){
            printf("Error\n");
            return;
        }
        int i=0, j;
        while(i < number)
        {   
            fscanf(f,"%s", person[i].name); // Break point at second loop through

            // Read numbers from txt file
            for(j=0; j<2; j++){
                fscanf(f, "%d", &person[i].array[j]);
            }
            if(feof(f)){
                break;
            }
            i++;
        }

        fclose(f);
    }

I also have function that prints data:

void printData(s_person *person, int number)
{
    int i, j;
    for(i=0; i<number; i++){
        printf("%s ", person[i].name);

        for(j=0; j<2;j++)
        {
            printf("%d ", person[i].array[j]);
        }
        printf("\n");   
    }
}

And main looks like this:

main()
{
    int number = 2;
    s_person *person = construct(number);
    getData(person, number);
    printData(person, number);
    free(person);
}

I think it's something with fscanf function that I did wrong but I haven't slights idea what.

It works perfectly if I have one row of data to read. ( int number = 1; ). But if it has to read more than one row it breaks at second run through while loop at fscanf(f,"%s", osoba[i].name);.


Solution

  • For every number of s_person there needs to be memory allocated for name and array

    s_person* construct(int number){
        int each;
        s_person *person = (s_person*)malloc(sizeof(s_person) * number);
        if ( person) {
            for (each = 0; each < number; each++){
                person[each].name = (char*)malloc(sizeof(char) * 50);
                person[each].array = (int*)malloc(sizeof(int) * 2);
            }
        }
        return person;
    }