I have an assignment to read a file with the list of months in order and store them which is done at the beginning of the program. 2nd I need to take another file with a list of dates such as
January 17,2004. (one on each line). I need to take that file and add a count/update a count for the that year and month. So that'd be January 2004 that would be updated. I think I'm planning on putting that in a structure later because it seems easiest to me at the moment.
I'm testing the strcmp in my for loop( line 62 )
Code:
for(i = 0; i < counter1; i++) {
test = strcmp(array_of_months[i].months, month);
if(test ==0)
printf("%d: %s\n", counter2, month);
}
and my output is giving me the correct output for the month of December and no other month.
for example..
4: December
12: December
I was hoping this for loop would be able to show that same output for every month. Basically trying to compare the Months I have already stored to the months I'm reading and if they match I was going to stick the years in a structure and use them later.
Why is this for loop only giving me the output for the month of December and no other months though?
Hope this is clear enough.
Thanks for any help. I'll attach my whole code so far below.
Code:
struct struct_of_months{
char months[20];
};
struct stuct_of_years
{
char year[4];
};
int main(void)
{
FILE *fp;
char buffer[50];
char **month_and_year = NULL;
int counter1 = 0;
int counter2 = 0;
int line_len;
char *month;
char *day;
char *year;
int i=0;
int test;
struct struct_of_months *array_of_months = malloc (sizeof(*array_of_months));
//Opens the first file and stores the months individually in list_of_months
if ( (fp = fopen("months.txt", "r" )) == NULL )
{
printf("Couldn't open file\n");
exit(1);
}
while(fgets(buffer, sizeof(buffer), fp))
{
if (counter1>0)
array_of_months=realloc(array_of_months,(counter1+1)*sizeof(*array_of_months));
strcpy(array_of_months[counter1].months, buffer);
counter1++;
}
fclose( fp );
//Opens the second file and stores the month in month and year in year.
if ( (fp = fopen("dates.csv", "r" )) == NULL )
{
printf("Couldn't open file\n");
exit(1);
}
while(fgets(buffer, sizeof(buffer), fp))
{
month_and_year = realloc(month_and_year, (counter2+1) * sizeof(*month_and_year) );
line_len = strlen(buffer);
month_and_year[counter2] = calloc(line_len+1, sizeof(buffer));
strcpy(month_and_year[counter2],buffer);
month = strtok (month_and_year[counter2], " ");
day = strtok (NULL, ",");
year = strtok (NULL, ",");
for(i = 0; i < counter1; i++)
{
test = strcmp(array_of_months[i].months, month);
if(test ==0)
printf("%d: %s\n", counter2, month);
}
counter2++;
}
fclose( fp );
free(month_and_year);
getchar();
return 0;
}