I am writing a C code that will read the data from a text file which contains the following data: name, age, income
After reading the data successfully, the data will be separated into two different files: In the first one all of the entries whose age is below the average
In the second one all of the entries whose income is above the average
However, my code only prints the last data into both files. I do not know what is wrong with my code.
What I have tried:
MY CODE
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct
{
char name[15];
int age;
float income;
} data;
void input(FILE*, data*);
void output1(FILE*, data*);
void output2(FILE* file2, data* data);
int main(void) {
data p;
data *place = &p;
char fileR[10] = "F1.txt", file1W[10] = "F2.txt", file2W[10] = "F3.txt";
float ave_income = 0, sum_income = 0;
int ave_age = 0, sum_age = 0, count = 0;
FILE *fi, *fo1, *fo2;
fi = fopen(fileR, "r");
fo1 = fopen(file1W, "w");
fo2 = fopen(file2W, "w");
do{
input(fi, place);
sum_age+=p.age;
++count;
}while(fgetc(fi)!=EOF);
ave_age = sum_age/count;
do{
if (p.age < ave_age)
{
output1(fo1, place);
}
else
{
continue;
}
}while(fgetc(fi)!=EOF);
do{
input(fi, place);
sum_income+=p.income;
}while(fgetc(fi)!=EOF);
ave_income = sum_income/count;
do{
if (p.income > ave_income)
{
output2(fo2, place);
}
else
{
continue;
}
}while(fgetc(fi)!=EOF);
fclose(fi);
fclose(fo1);
fclose(fo2);
return 0;
}
void input(FILE* f, data* data)
{
fscanf(f, "%s %d %f", data->name,&data->age,&data->income);
}
void output1(FILE* file, data* data)
{
fprintf(file, "Name %s \nAge: %d\nWind Income: %f \n", data->name, data->age, data->income ); printf("Name %s \nAge: %d\nIncome: %f \n",data->name, data->age, data->income); }
void output2(FILE* file2, data* data)
{
fprintf(file2, "Name %s \nAge: %d\nWind Income: %f \n", data->name, data->age, data->income ); printf("Name %s \nAge: %d\nIncome: %f \n",data->name, data->age, data->income);
TEXT FILE
Alex 25 670
John 24 830
Jessica 31 800
Milana 27 680
Kaarel 28 1200
Triin 34 1300
Maria 29 1450
Jaanus 28 1350
Maaris 26 1100