Initial import of a bitmap implementation as part of a filesystem project
[eleutheria.git] / homework / bitmap.c
blobeec963700a0ef07bd459f207b53a40c4597f6322
1 #include <limits.h> /* for CHAR_BIT */
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h> /* for memset() */
6 int is_blk_free(const unsigned char *array, unsigned int nblk);
7 void print_blks(const unsigned char *array, unsigned int nblks);
8 void diep(const char *s);
10 int main(int argc, char *argv[])
12 unsigned char *array;
13 unsigned int i, narr, nblks, u;
15 /* Check argument count */
16 if (argc != 2) {
17 fprintf(stderr, "Usage: %s nblocks\n", argv[0]);
18 exit(EXIT_FAILURE);
21 /* Get number of blocks */
22 nblks = (unsigned int) strtoul(argv[1], NULL, 10);
23 u = nblks - CHAR_BIT * (nblks / CHAR_BIT);
24 if (u == 0)
25 narr = nblks / CHAR_BIT;
26 else
27 narr = nblks / CHAR_BIT + 1;
28 printf("nblks = %u\tnarr = %u\n", nblks, narr);
30 /* Allocate memory for char bitmap */
31 array = malloc(narr);
32 if (array == NULL)
33 diep("malloc");
35 /* Initialize all bits to 0 representing free blocks */
36 memset(array, 0, narr);
38 /* Print blocks' status */
39 print_blks(array, nblks);
41 /* Flag all blocks as used */
42 for (i = 0; i < narr; i++)
43 array[i] = 0xFF;
44 print_blks(array, nblks);
46 /* Free bitmap */
47 free(array);
49 return EXIT_SUCCESS;
52 int is_blk_free(const unsigned char *array, unsigned int nblk)
54 unsigned int idx, u;
56 idx = nblk / CHAR_BIT;
57 u = nblk - CHAR_BIT * idx;
58 printf("blk %u is in array %u and bitpos %u\n",
59 nblk, idx, u);
61 return ((array[idx] & (1 << u)) == 0);
64 void print_blks(const unsigned char *array, unsigned int nblks)
66 unsigned int i;
68 for (i = 0; i < nblks; i++)
69 printf("blk[%04u] = %s\n",
70 i, is_blk_free(array, i) ? "FREE" : "USED");
73 void diep(const char *s)
75 perror(s);
76 exit(EXIT_FAILURE);