I'm trying to combine structures and files. So, I want to read n elements of the structure in the data file.txt., there can be N records, (in my case day, month and year), and then manipulate this data, and the result to enroll in another file. Could you help me with that? I'd be very grateful. Here's my code
#include <stdio.h>
struct data{
int d, m, y;
};
void readN(struct data element[],int n){
FILE *data_file;
data_file = fopen("data.txt","r");
if(data_file == NULL){
fprintf(stderr, "\n Error!!!");
}
else{
while(!feof(data_file)){
fscanf(data_file,"%d %d %d", &element->d, &element->m, &element->y);
}
}
}
int compareDates (struct data d1, struct data d2)
{
if (d1.y < d2.y)
return -1;
else if (d1.y > d2.y)
return 1;
else if (d1.m < d2.m)
return -1;
else if (d1.m > d2.m)
return 1;
else if (d1.d < d2.d)
return -1;
else if (d1.d > d2.d)
return 1;
else
return 0;
}
struct data checkMax(struct data *element, int n){
struct data max = element[0];
int i;
for (i = 0; i < n; i++){
if(compareDates(max,element[i]) == -1){
max = element[i];
}
}
return max;
}
struct data checkMin(struct data *element, int n) {
struct data min = element[0];
int i;
for (i = 0; i < n; i++){
if(compareDates(min,element[i]) == 1){
min = element[i];
}
}
return min;
}
int checkLeapYear(struct data yMax, struct data yMin){
int counter = 0;
for(int i = yMin.y; i <= yMax.y; i++ ){
if((i % 4 == 0 && i % 100 != 0) || i % 400 == 0){
counter++;
}
}
return counter;
}
int main() {
struct data dd1[4];
readN(dd1,4);
struct data maximum = checkMax(dd1,4);
struct data minimum = checkMin(dd1,4);
printf("\n Data maxima %d %d %d",maximum.d,maximum.m,maximum.y);
printf("\n Data minima %d %d %d", minimum.d,minimum.m,minimum.y);
printf("\n Nr de ani bisecti : %d ", checkLeapYear(maximum,minimum));
return 0;
}
data.txt
10 10 2001
1 1 2002
14 3 2004
18 4 2022
My console
Data maxima 6422280 1986752301 4201664
Data minima 1986776256 2133694049 -2
Nr de ani bisecti : 1018905
Error!!!