-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdatabaseOperationWithMMAP.c
116 lines (96 loc) · 2.55 KB
/
databaseOperationWithMMAP.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#define PAGE_SIZE 4096
#define MAX_RECORDS 100
typedef struct {
int id;
char name[50];
} Record;
typedef struct {
int record_count;
Record records[MAX_RECORDS];
} Database;
void* map_file(const char* filename, size_t* size) {
int fd = open(filename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (fd == -1) {
perror("Error opening file");
return NULL;
}
struct stat sb;
if (fstat(fd, &sb) == -1) {
perror("Error getting file size");
close(fd);
return NULL;
}
*size = sb.st_size;
// If the file is empty, initialize it with the Database structure
if (*size == 0) {
*size = sizeof(Database);
if (ftruncate(fd, *size) == -1) {
perror("Error setting file size");
close(fd);
return NULL;
}
}
void* addr = mmap(NULL, *size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (addr == MAP_FAILED) {
perror("Error mapping file");
close(fd);
return NULL;
}
close(fd);
return addr;
}
int insert_record(Database* db, int id, const char* name) {
if (db->record_count >= MAX_RECORDS) {
printf("Database is full\n");
return 0;
}
Record* record = &db->records[db->record_count];
record->id = id;
strncpy(record->name, name, sizeof(record->name) - 1);
record->name[sizeof(record->name) - 1] = '\0';
db->record_count++;
return 1;
}
Record* find_record(Database* db, int id) {
for (int i = 0; i < db->record_count; i++) {
if (db->records[i].id == id) {
return &db->records[i];
}
}
return NULL;
}
int main() {
size_t size;
Database* db = (Database*)map_file("database.dat", &size);
if (!db) {
return 1;
}
// Insert some records
insert_record(db, 1, "Alice");
insert_record(db, 2, "Bob");
insert_record(db, 3, "Charlie");
// Find and print a record
Record* record = find_record(db, 2);
if (record) {
printf("Found record: ID=%d, Name=%s\n", record->id, record->name);
} else {
printf("Record not found\n");
}
// Print all records
printf("All records:\n");
for (int i = 0; i < db->record_count; i++) {
printf("ID=%d, Name=%s\n", db->records[i].id, db->records[i].name);
}
// Unmap the file
if (munmap(db, size) == -1) {
perror("Error unmapping file");
}
return 0;
}