You have the right idea, but this should fix your problem.
for (int var = 0; var < i; ++var) {
fwrite(&S[i], sizeof(struct Student), 1, sourcefile);
}
The argument 1 in fwrite
after the sizeof
statement indicates you only want to add one Student at a time.
Please see the doc for fwrite
: http://www.cplusplus.com/reference/cstdio/fwrite/
And also:
while (fgetc(sourcefile) != EOF) {
fread(&A[k], sizeof(struct Student), 1, sourcefile);
k++;
}
Please see the doc for fread
: http://www.cplusplus.com/reference/cstdio/fread/
I know it's the cplusplus website, but it's the only place I could find good docs on the functions.
Also, the below array initializes to 0 elements:
struct Student A[k];
You may want to try managing a linked list for this instead.
Might end up looking something like:
struct StudentList {
struct Student* student;
struct StudentList* next;
};
struct StudentList* students = NULL;
while(!feof(sourcefile)) {
struct StudentList* newlink = malloc(sizeof(struct StudentList));
newlink->student = malloc(sizeof(struct Student));
newlink->next = NULL;
fread(newlink->student, sizeof(struct Student), 1, sourcefile);
if(NULL != students) {
struct StudentList* iter;
for(iter=students;
NULL != iter->next;
iter = iter->next); // iterate to last link
iter->next = newlink; // add new link to the end
} else students = newlink; // add new link to the beginning
}
Then to free your list, just use something like:
struct StudentList* iter, *head;
for(iter=students;
NULL != iter;)
{
head = iter;
free(iter->student);
free(iter);
iter = head;
}