Writing and modifying data in a file
I decided to write simple database program.
It is a database in which student's data are represented like this
Because program should allow user to enter new records, change records and list records I decided to use linked list because it is dinamical structure.
typedef struct student
unsigned long stud_id;
struct student* next;
All iformations should be saved in appropriate file.
Writing to a file is something like this:
And that is OK.
while(head != NULL)
fwrite(head,sizeof(student),1,fp)/*fp is FILE pointer*/
head = head->next;
Now assume there are already records saved in the file. When user starts program, data file is opened and data must be loaded. Now I need to decide what approach to use. One idea is to form a new linked list from data in the file and when saving, file is overwritten and new (and updated) data are written. Obviously for large number of records this is slow and unappropriate.
Second choice is to work with data in file directly. For example user need to change data of student with some specific ID. First it is necessary to find that record posibly using something like this:
Then a new updated record needs to be written instead. I think to achive this with following code
fread(stud,sizeof(student),1,fp)/* stud is a pointer to student*/
}while(stud->sutd_id != ID);
With this approach I'll save time but I don't know how clever it is to write and change data directly in file.
/*change data in stud*/
fseek(fp,-(int)sizeof(student),SEEK_CUR);/* go back one record*/
fwrite(stud,sizeof(student),1,fp);/* write updated record*/
I hope you understand my dillema. I'll need your advices on how to plan this before I start coding. Maybe there is another (better) approach.
Thank you all for help!