'Reading the contents of a file containing structure variables

I have a program that processes calendar date type structures (day, month , year). How can I read the content of a file, regardless of the number of records in it?. at the moment, my code only reads the number of records I send as a parameter, which is not exactly correct and useful.

This is my function

void readN(struct data *element,int n){
    FILE *data_file;
    data_file = fopen("D:\\univer\\sem2\\tehProg\\struct_and_files\\data.txt","r");
    if(data_file == NULL){
        fprintf(stderr, "Unable to open file\n");
        return;
    }
    for (int i = 0; i < n; i++) {
        if (fscanf(data_file,"%d %d %d", &element[i].d, &element[i].m, &element[i].y) != 3){
            fprintf(stderr, "Incomplete input!!!\n");
            break;
        }
    }
    fclose(data_file);
}
int main() {

   struct data dd1[4];
    readN(dd1,4);

    return 0;
}

data.txt content

10 10 2001
1 1  2002
14 3 2004
18 4 2022
17 10 2002
c


Solution 1:[1]

In pseudo code it could be something like this:

struct data *elements = NULL;

char line[SOME_GOOD_SIZE];
int n = 0;

while (fgets(line, sizeof line, file))
{
    int y, m, d;
    if (parse_line(line, &y, &m, &d))
    {
        elements = reallocate(elements, n + 1);

        elements[n].d = d;
        // etc...

        ++n;
    }
}

Once finished you have either read all lines from the file (or ended early if there was an error, you need to handle that), and you can return the pointer elements from the function.

Read more about the realloc function and what it does. Pay close attention to what it returns, and what the arguments really are.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Some programmer dude