#include #include typedef struct student{ char name [20]; int id; }student; /* 1 if success 0 if fail -1 if filename pb -2 empty file */ int writeArStd(char * filename, student *s, int size){ unsigned long ans; //open the file FILE *f = fopen(filename, "wb"); //test open if(!f){ return -1; } //try to write ans = fwrite(s, sizeof (student), size, f); //test if write was success if (ans != size){ return 0; } //save the file ans = fclose(f); //test if close success: if (ans != 0){//fclose will return 0 in case of success! return 0; } return 1; } student * readArStd(char * filename, int *size){ //first - we have to return the array of students, so we have to allocate it // inside the heap so we avoid TAB-Victim problem //second- we do not really know the size of the array to be read(and so) to // be allocated in the heap //third- when we know the size, we will also return it inside *s unsigned long ans, r = 0; student s, *p = NULL; // I need one local variable to count int counter = 0; //open the file FILE *f; if(!(f = fopen(filename, "rb"))) return NULL; while(1){ if (fread(&s, sizeof s, 1, f) != 1) break; counter++; } //I am here because I tried to read 1 student //And did not succeed //That is because I reached the end of the file // (feof(f)) --> return 1; if (counter != 0){ *size = counter; //alocate the array in the heap p = (student *) malloc( counter * sizeof(student)); //rewind f rewind(f);//set the file position indicator at the beginning //fseek would do //read in one shot fread(p, sizeof s, counter, f); } //close the file ans = fclose(f); return p; } void printStudent(student s){ printf("student [name = %s, id = %d ]\n", s.name, s.id); } void test(){ char *fname = "students"; int array_size = 0, i; student *stds, students [] ={"Ali Berro",97206, "Amir Halabi",98613, "Ali Noureldin",96366, "Nidal Jaafar",95135}; int s = sizeof(students)/sizeof(student); //for(i=0 ; i