1
0
Fork 0

07: C: Use mmap instead of fgets

This commit is contained in:
Mia Herkt 2022-12-07 23:51:13 +01:00
parent 97294b6cf8
commit 5cb23bf245
Signed by: mia
GPG Key ID: 72E154B8622EC191
1 changed files with 20 additions and 6 deletions

View File

@ -2,6 +2,9 @@
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
uint32_t fnv1a_32(const char *buf, size_t len)
{
@ -22,7 +25,7 @@ typedef struct entry {
} entry;
entry *findent(entry *e, const char *name) {
uint32_t id = fnv1a_32(name, strlen(name));
uint32_t id = fnv1a_32(name, strchr(name, '\n') - name);
for (size_t i = 0; i < e->n_entries; i++) {
if (e->entries[i]->id == id)
return e->entries[i];
@ -42,19 +45,29 @@ entry *addent(entry *parent, const char *name) {
parent->n_entries++;
entry *e = parent->entries[parent->n_entries - 1] = calloc(1, sizeof(entry));
e->id = fnv1a_32(name, strlen(name));
e->id = fnv1a_32(name, strchr(name, '\n') - name);
e->parent = parent;
return e;
}
int main(int argc, char **argv) {
char l[64];
if (argc < 2) return 1;
entry *root = calloc(1, sizeof(entry));
entry *current = root;
size_t S = 0, G = 0, required = 0;
while (fgets(l, 64, stdin)) {
struct stat s;
if (stat(argv[1], &s) == -1) return 1;
int fd = open(argv[1], O_RDONLY);
if (fd == -1) return 1;
char *in = mmap(NULL, s.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (in == MAP_FAILED) return 1;
char *l = in;
while (l - in < s.st_size) {
if (l[0] == '$') {
if (l[2] == 'c') {
if (l[5] == '/')
@ -73,11 +86,12 @@ int main(int argc, char **argv) {
f->size += sz;
f->size += sz;
}
l = strchr(l, '\n') + 1;
}
current = root;
if (argc == 3)
required = strtoul(argv[2], NULL, 10) - (strtoul(argv[1], NULL, 10) - root->size);
if (argc == 4)
required = strtoul(argv[3], NULL, 10) - (strtoul(argv[2], NULL, 10) - root->size);
else
required = 30000000UL - (70000000UL - root->size);
do {