From f768ac2c4a17c81033eca5d1cbc2fc490a4e737c Mon Sep 17 00:00:00 2001 From: Ali Gholami Rudi Date: Thu, 5 Mar 2009 10:22:50 +0330 Subject: [PATCH] quran: use mmap() instead of read() --- quran.c | 27 ++++++++------------------- quran.h | 1 + 2 files changed, 9 insertions(+), 19 deletions(-) diff --git a/quran.c b/quran.c index 3e8c305..e4713e5 100644 --- a/quran.c +++ b/quran.c @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -7,29 +8,14 @@ #include "util.h" #include "quran.h" -static size_t file_size(char *path) +static size_t file_size(int fd) { struct stat st; - if (!stat(path, &st)) + if (!fstat(fd, &st)) return st.st_size; return 0; } -static char *file_read(char *path) -{ - char *buf; - int fd; - int c = 0; - int n = 0; - size_t size = file_size(path); - buf = xmalloc(size); - fd = open(path, O_RDONLY); - while ((c = read(fd, buf + n, size - n)) > 0) - n += c; - close(fd); - return buf; -} - static int newlines(char *s) { int n; @@ -43,7 +29,9 @@ struct quran *quran_alloc(char *path) int nayas; struct quran *quran = xmalloc(sizeof(struct quran)); memset(quran, 0, sizeof(quran)); - quran->text = file_read(path); + quran->fd = open(path, O_RDONLY); + quran->text = mmap(NULL, file_size(quran->fd), PROT_READ, + MAP_SHARED, quran->fd, 0); nayas = newlines(quran->text); quran->ayas = xmalloc(sizeof(quran->ayas) * nayas); quran->ayas[0] = quran->text; @@ -65,8 +53,9 @@ void quran_aya(struct quran *quran, char *buf, size_t len, int aya) void quran_free(struct quran *quran) { + munmap(quran->text, file_size(quran->fd)); + close(quran->fd); free(quran->ayas); - free(quran->text); free(quran); } diff --git a/quran.h b/quran.h index a56731f..f951300 100644 --- a/quran.h +++ b/quran.h @@ -4,6 +4,7 @@ #define NSURA 114 struct quran { + int fd; char *text; char **ayas; }; -- 2.11.4.GIT