3 * gcc bitmap.c -o bitmap -Wall -W -Wextra -ansi -pedantic
6 #include <limits.h> /* for CHAR_BIT */
9 #include <string.h> /* for memset() */
13 #define DPRINTF(x) printf x
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
[])
26 unsigned int i
, narr
, nblks
, u
;
28 /* Check argument count */
30 fprintf(stderr
, "Usage: %s nblocks\n", argv
[0]);
34 /* Get number of blocks */
35 nblks
= (unsigned int) strtoul(argv
[1], NULL
, 10);
36 u
= nblks
- CHAR_BIT
* (nblks
/ CHAR_BIT
);
38 narr
= nblks
/ CHAR_BIT
;
40 narr
= nblks
/ CHAR_BIT
+ 1;
41 printf("Requested nblks = %u\tAllocating narr = %u chars\n", nblks
, narr
);
43 /* Allocate memory for char bitmap */
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
++)
57 print_blks(array
, nblks
);
65 int is_blk_free(const unsigned char *array
, unsigned int nblk
)
69 idx
= nblk
/ CHAR_BIT
;
70 u
= nblk
- CHAR_BIT
* idx
;
71 DPRINTF(("blk %u is in array %u and bitpos %u\n",
74 return ((array
[idx
] & (1 << u
)) == 0);
77 void print_blks(const unsigned char *array
, unsigned int nblks
)
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
)