I'm having an aggravating issue that I can't understand,
void file_count(FILE* stream,int* const num)
{
int temp;
while((fscanf(stream,"%d",&temp))!=EOF)
{
(*num)++;
}
}
With this piece of program, I read from a file taking all the numbers inside it, and very time I take a number a counter increases so I can count how many elements are in the file.
In this file there are 6 numbers, but if I run this code the counter skyrockets to 32777... If I compile it with gcc, there's no problem and the counter is 6 as expected. Is this a bug of clang? Is it a feature that I'm not aware of?
The file contains:
22 30 30 21 25 29
The whole code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char* string;
typedef struct student
{
int flag;
char name[25];
char surname[25];
char dorm[25];
int* grades;
}
Student;
void check_input(const int argc,const string* const argv);
void check_file(FILE* stream);
void file_count(FILE* stream,int* const num);
void update_student(const string* const infos,Student* const student,const int grades,FILE* stream);
void print_student(FILE* stream,Student const student,const int grades);
int main(int argc, string argv[])
{
check_input(argc,argv);
FILE* one,* two;
string info[]={"David","Malan","Mather"};
Student student;
int grades;
one=fopen(argv[1],"r");
check_file(one);
file_count(one,&grades);
update_student(info,&student,grades,one);
fclose(one);
two=fopen(argv[2],"w");
check_file(two);
print_student(two,student,grades);
fclose(two);
free(student.grades);
system("cat out");
return 0;
}
void check_input(const int argc,const string* const argv)
{
if(argc!=3)
{
printf("\x1B[31mError: %s takes two arguments!\x1B[0m\n",argv[0]);
exit(EXIT_FAILURE);
}
}
void check_file(FILE* stream)
{
if(stream==NULL)
{
printf("\x1B[31mError:invalid file.\x1B[0m\n");
exit(EXIT_FAILURE);
}
}
void file_count(FILE* stream,int* const num)
{
int temp;
printf("reading file...\n");
while((fscanf(stream,"%i",&temp))!=EOF)
{
(*num)++;
}
printf("\x1B[33mthe value read were %i\x1B[0m\n",*num);
}
void update_student(const string* const infos,Student* const student,const int grades,FILE* stream)
{
rewind(stream);
student->grades=malloc(grades*sizeof(int));
strcpy(student->name,infos[0]);
strcpy(student->surname,infos[1]);
strcpy(student->dorm,infos[2]);
student->flag=0;
for(int i=0;i<grades;i++)
{
fscanf(stream,"%i",&student->grades[i]);
}
}
void print_student(FILE* stream,Student const student,const int grades)
{
printf("Writing to file..\n");
fprintf(stream,"%i %s %s %s ",student.flag,student.name,student.surname,student.dorm);
for(int i=0;i<grades;i++)
{
fprintf(stream,"%i ",student.grades[i]);
}
printf("\x1B[32mFile successfully written..\x1B[0m\n");
}