This repository was archived by the owner on Aug 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathtask4.c
More file actions
116 lines (96 loc) · 2.34 KB
/
task4.c
File metadata and controls
116 lines (96 loc) · 2.34 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FILE_SIZE 10
#define MAX_BUFF_SIZE 20
#define MAX_file_COUNT 10
void read_data(char* buff, size_t buff_size) {
int c;
int idx = 0;
while (c = fgetc(stdin)) {
if (idx == buff_size) {
break;
}
buff[idx++] = c;
}
printf("Read %d bytes\n", idx);
}
void read_line(char* buff) {
int c;
int idx = 0;
while (c = fgetc(stdin)) {
if (c == '\n') {
break;
}
buff[idx++] = c;
}
}
char *files[MAX_file_COUNT] = { 0 };
void create_file(size_t size) {
for (int i = 0; i < MAX_file_COUNT; i++) {
if (files[i] == NULL) {
files[i] = malloc(size);
read_data(files[i], size);
printf("file id: %d\n", i);
return;
}
}
printf("Database is full, you must delete a file before creating a new one!");
}
void delete_file(int file_id) {
if (files[file_id] != NULL) {
free(files[file_id]);
printf("file deleted\n");
} else {
printf("file does not exist\n");
}
}
char* get_file(int file_id) {
return files[file_id];
}
void print_help() {
printf("\nCommands:\n");
printf("create [file_size] - create a new file\n");
printf("read [file_id] - get file contents\n");
printf("delete [file_id] - delete a file\n");
printf("exit\n\n");
}
void cmd_handler() {
char buff[MAX_BUFF_SIZE];
char *file_data;
while(1) {
read_line(buff);
if (strncmp(buff, "read", 4) == 0) {
int file_id = atoi(&buff[5]);
file_data = get_file(file_id);
if (file_data != NULL) {
printf("FILEDATA:");
puts(file_data);
}
} else if (strncmp(buff, "create", 6) == 0) {
int file_size = atoi(&buff[7]);
if (file_size == 0) {
printf("File cannot be empty\n");
continue;
}
if (file_size >= MAX_FILE_SIZE) {
printf("file size is too large! :(\n");
continue;
}
create_file(file_size);
} else if (strncmp(buff, "delete", 6) == 0) {
int file_id = atoi(&buff[7]);
delete_file(file_id);
} else if (strncmp(buff, "exit", 4) == 0) {
printf("Good bye!\n");
break;
} else {
printf("\n404 - COMMAND NOT FOUND\n");
}
}
}
int main(int argc, const char* argv[]) {
printf("Welcome to ultra fast and HACKER-PROOF in-memory file database version 1337!\n");
print_help();
cmd_handler();
}