Hi,
I decided to write simple database program.
It is a database in which student's data are represented like this
Code:
typedef struct student
{
char first_name[31];
char last_name[31];
unsigned long stud_id;
struct student* next;
}student;
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.
All iformations should be saved in appropriate file.
Writing to a file is something like this:
Code:
while(head != NULL)
{
fwrite(head,sizeof(student),1,fp)/*fp is FILE pointer*/
head = head->next;
}
And that is OK.
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:
Code:
do{
fread(stud,sizeof(student),1,fp)/* stud is a pointer to student*/
}while(stud->sutd_id != ID);
Then a new updated record needs to be written instead. I think to achive this with following code
Code:
/*change data in stud*/
fseek(fp,-(int)sizeof(student),SEEK_CUR);/* go back one record*/
fwrite(stud,sizeof(student),1,fp);/* write updated record*/
With this approach I'll save time but I don't know how clever it is to write and change data directly in file.
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!