I hope someone can help me. I'm trying to read file that consists of some amount of structs from below:
struct query {
int key;
char surname[16];
char name[16];
char patronymic[16];
char subject[16];
int grade;
}s;
I need to use mmap()
to read some data from file, for example to print all structs with same subject and grade, or print a query that has specific key.
In any other case I would use fopen()
and fread()
to read file with my structs. Something like this:
FILE *inputFile;
inputFile = fopen("database.dat", "rb");
while(fread(&s, sizeof(s), 1, inputFile) == 1) {
printf("\nKey: %d", s.key);
printf("\nName: %s", s.name);
printf("\nSurname: %s", s.surname);
printf("\nPatronymic: %s", s.patronymic);
printf("\nSubject: %s", s.subject);
printf("\nGrade: %d", s.grade);
}
But I can't get my head around mmap()
so I have a few questions:
- How do I initialize
mmap()
with my file in first place? I imagine something like this but I'm not sure (let's say that I know how much structs in file, let it beamount
andfd
is my proprer file descriptor).
mmap(NULL, amount*sizeof(s), PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0);
Also what type of variable I assign this to so I can work with it?
- How do I go through all the structs in mapped file and compare their fields? Normally (with
fread()
) I would just do nested cycles. But I have no idea what to do in mapped case. - Is it possible to
mmap()
file without knowing amount of structs? In first question I assumed that I know file length (amount*sizeof(s)
). Can I map file without knowingamount
?
I'm sorry if my terminology sounds off, I'm not really good at English.