Die only argc < 2
[eleutheria.git] / homework / bitmap.c
blob04c3c01a28b8f0ebb41c3db61c318d5698643f31
1 /*
2 * Compile with:
3 * gcc bitmap.c -o bitmap -Wall -W -Wextra -ansi -pedantic
4 */
6 #include <limits.h> /* for CHAR_BIT */
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h> /* for memset() */
11 /* #define DEBUG */
12 #ifdef DEBUG
13 #define DPRINTF(x) printf x
14 #else
15 #define DPRINTF(x)
16 #endif
18 /* Function prototypes */
19 int is_blk_free(const unsigned char *array, unsigned int nblk);
20 void print_blks(const unsigned char *array, unsigned int nblks);
21 void diep(const char *s);
23 int main(int argc, char *argv[])
25 unsigned char *array;
26 unsigned int i, narr, nblks, u;
28 /* Check argument count */
29 if (argc != 2) {
30 fprintf(stderr, "Usage: %s nblocks\n", argv[0]);
31 exit(EXIT_FAILURE);
34 /* Get number of blocks */
35 nblks = (unsigned int) strtoul(argv[1], NULL, 10);
36 u = nblks - CHAR_BIT * (nblks / CHAR_BIT);
37 if (u == 0)
38 narr = nblks / CHAR_BIT;
39 else
40 narr = nblks / CHAR_BIT + 1;
41 printf("Requested nblks = %u\tAllocating narr = %u chars\n", nblks, narr);
43 /* Allocate memory for char bitmap */
44 array = malloc(narr);
45 if (array == NULL)
46 diep("malloc");
48 /* Initialize all bits to 0 representing free blocks */
49 memset(array, 0, narr);
51 /* Print blocks' status */
52 print_blks(array, nblks);
54 /* Flag all blocks as used */
55 for (i = 0; i < narr; i++)
56 array[i] = 0xFF;
57 print_blks(array, nblks);
59 /* Free bitmap */
60 free(array);
62 return EXIT_SUCCESS;
65 int is_blk_free(const unsigned char *array, unsigned int nblk)
67 unsigned int idx, u;
69 idx = nblk / CHAR_BIT;
70 u = nblk - CHAR_BIT * idx;
71 DPRINTF(("blk %u is in array %u and bitpos %u\n",
72 nblk, idx, u));
74 return ((array[idx] & (1 << u)) == 0);
77 void print_blks(const unsigned char *array, unsigned int nblks)
79 unsigned int i;
81 for (i = 0; i < nblks; i++)
82 printf("blk[%04u] = %s\n",
83 i, is_blk_free(array, i) ? "FREE" : "USED");
86 void diep(const char *s)
88 perror(s);
89 exit(EXIT_FAILURE);