From 2fb5ad365949ecff6edf1a4a910428e667233299 Mon Sep 17 00:00:00 2001 From: Stathis Kamperis Date: Fri, 11 Jan 2008 20:06:25 +0100 Subject: [PATCH] Initial import of a bitmap implementation as part of a filesystem project --- homework/bitmap.c | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 homework/bitmap.c diff --git a/homework/bitmap.c b/homework/bitmap.c new file mode 100644 index 0000000..eec9637 --- /dev/null +++ b/homework/bitmap.c @@ -0,0 +1,77 @@ +#include /* for CHAR_BIT */ +#include +#include +#include /* for memset() */ + +int is_blk_free(const unsigned char *array, unsigned int nblk); +void print_blks(const unsigned char *array, unsigned int nblks); +void diep(const char *s); + +int main(int argc, char *argv[]) +{ + unsigned char *array; + unsigned int i, narr, nblks, u; + + /* Check argument count */ + if (argc != 2) { + fprintf(stderr, "Usage: %s nblocks\n", argv[0]); + exit(EXIT_FAILURE); + } + + /* Get number of blocks */ + nblks = (unsigned int) strtoul(argv[1], NULL, 10); + u = nblks - CHAR_BIT * (nblks / CHAR_BIT); + if (u == 0) + narr = nblks / CHAR_BIT; + else + narr = nblks / CHAR_BIT + 1; + printf("nblks = %u\tnarr = %u\n", nblks, narr); + + /* Allocate memory for char bitmap */ + array = malloc(narr); + if (array == NULL) + diep("malloc"); + + /* Initialize all bits to 0 representing free blocks */ + memset(array, 0, narr); + + /* Print blocks' status */ + print_blks(array, nblks); + + /* Flag all blocks as used */ + for (i = 0; i < narr; i++) + array[i] = 0xFF; + print_blks(array, nblks); + + /* Free bitmap */ + free(array); + + return EXIT_SUCCESS; +} + +int is_blk_free(const unsigned char *array, unsigned int nblk) +{ + unsigned int idx, u; + + idx = nblk / CHAR_BIT; + u = nblk - CHAR_BIT * idx; + printf("blk %u is in array %u and bitpos %u\n", + nblk, idx, u); + + return ((array[idx] & (1 << u)) == 0); +} + +void print_blks(const unsigned char *array, unsigned int nblks) +{ + unsigned int i; + + for (i = 0; i < nblks; i++) + printf("blk[%04u] = %s\n", + i, is_blk_free(array, i) ? "FREE" : "USED"); +} + +void diep(const char *s) +{ + perror(s); + exit(EXIT_FAILURE); +} -- 2.11.4.GIT