How do I read from a file and store it into an array of structures?

Viewed 54

I have a file with the data:

30 101 201 35
31 102 203 35
31 103 202 35
32 103 201 50
33 102 203 40
33 103 202 105
33 101 201 70

And a structure:

struct data
{
    int day;
    int emp;
    int pro;
    int sal;
};

I want to read the entire file and store it to a structure array and then print it. This is what I have:

int main()
{
    FILE *file=NULL;
    struct data salesarr[10];
    int i;

        file=fopen("Sales Report.txt","r");
        //Error Function
        if(file == NULL)
        {
            printf("Error!");
            exit(1);
        }
        
            for(i=0;i<10;i++)
            {
                fscanf(file,"%d %d %d %d",salesarr[i].day,salesarr[i].emp,salesarr[i].pro,&salesarr[i].sal);
                printf("%d %d %d %d\n",salesarr[i].day,salesarr[i].emp,salesarr[i].pro,salesarr[i].sal);
            }

        }

I'm aware there's simpler ways to read and print the entire file, but I want to put it to a structure array so I can do other stuff with it, like sorting.

0 Answers
Related