Well
I agree with you in all possible ways,
First because i've tried to modify a previous code I have written to match the requirements of the actual assignment.
I need a better Idea to retrieve the data from the file, sort it. and then rewrite it in the same file(which I didn't know how to do it), or to another file.
so here is a funxtion that fills the array.
Code:
void fill_up_stu(student x[],FILE* ptr){
while(!(ptr=fopen("student.txt","w")))
printf("Cannot open file, Retry:\n");
for (int i = 0 ; i < MAX ; i++){
printf("First name: ");
scanf("%s",x[i].first_name);
fprintf(ptr,"%s ",x[i].first_name);
printf("Last name: ");
scanf("%s",x[i].last_name);
fprintf(ptr,"%s\n",x[i].last_name);
printf("GPA (Less than or equal 4): ");
scanf("%lf",&x[i].GPA);
fprintf(ptr,"%.2lf\n",x[i].GPA);
}
fclose(ptr);
}
I don't know, but the identation seems to be different when a past if in the website.
and now I need to sort that data in the file..what I'm sending there is a structure containing a firt name, last name and a GPA!!
the code for sorting, it obviously the source of the problem since my program craches at this place.
Code:
void selection_sort_stu(student x[], FILE * ptr){
int result;
int min;
FILE *ptr_up;
if(!(ptr=fopen("student.txt","r"))){
printf("Cannot open file.\n");
exit(1);
}
if(!(ptr_up=fopen("student_updated.txt","w"))){
printf("Cannot open file.\n");
exit(1);
}
for (int i = 0 ; i < MAX - 1 ; i++){
min = i;
fscanf(ptr,"%s",x[i].first_name);
for (int j = i + 1 ; j < MAX; j++){
fscanf(ptr,"%s",x[j].first_name);
if ((result = strcmp(x[i].first_name,x[j].first_name)) > 0)
min = j;
else if (!(result = strcmp(x[i].first_name,x[j].first_name))){
if ((result = strcmp(x[i].last_name,x[j].last_name))>0)
min = j;
}
}
fprintf(ptr_up,"%15s %15s %15.2lf\n",x[min].first_name,x[min].last_name,x[min].GPA);
fprintf(ptr_up,"%15s %15s %15.2lf\n",x[i].first_name,x[i].last_name,x[i].GPA);
}
fclose(ptr);
Thanks again!