Small Application C

#include
#include
#include
#define PACKAGE "dbits"
#define VERSION "0.0.1"
/* status epilepticus, print help and exit with exval */
void print_help(int exval);
/* print version and exit with exval */
void print_version(int exval);
int main(int argc, char *argv[]) {
FILE *fp = NULL;
char byte;
char dlmt = ' ';
int opt, bit, width, x;
int max_width = 8;
opt = bit = width = x = 0;
/* any options given ? */
if(argc == 1)
print_help(1);
/* option parser */
while((opt = getopt(argc, argv, "hvw:d:")) != -1) {
switch(opt) {
case 'h': /* print this help and exit */
print_help(0);
case 'v': /* print program version and exit */
print_version(0);
case 'w': /* set width to INT */
max_width = strtol(optarg, (char **)NULL, 10);
break;
case 'd': /* delimit bits with.. `dlmnt' */
sscanf(optarg, "%c", &dlmt);
break;
case '?': /* no such option */
fprintf(stderr, "%s: Error - No such option: `%c'\n\n", PACKAGE, optopt);
print_help(1);
case ':': /* option needs an argument */
fprintf(stderr, "%s: Error - option `%c' needs an argument\n\n", PACKAGE, optopt);
print_help(1);
}
}
/* there should be one remaining argument left, `FILE' */
if((argc - optind) == 0) {
fprintf(stderr, "%s: Error - Missing input file\n", PACKAGE);
return 1;
}
/* open & read file */
if((fp = fopen(argv[optind], "r")) == NULL) {
fprintf(stderr, "%s: Error - fopen(%s)\n", PACKAGE, argv[optind]);
return 1;
}
/* get bits... */
while(!feof(fp)) {
/* read one byte */
fread(&byte, 1, 1, fp);
/* iterate thru the 8 bits */
for(bit = 0; bit < 8; bit++) {
/* get least significant bit */
x = byte & 0x01;
printf("%d", x);
/* shift right */
byte = byte >> 1;
}
printf("%c", dlmt), width++;
if(width >= max_width)
printf("\n"), width = 0;
}
/* done.. */
printf("\n");
fclose(fp);
return 0;
}
/* status epilepticus, print help and exit with exval */
void print_help(int exval) {
printf("%s,%s dump bits\n", PACKAGE, VERSION);
printf("Usage: %s [-h] [-v] [-w INT] [-d CHAR] FILE\n\n", PACKAGE);
printf(" -h print this help and exit\n");
printf(" -v print version and exit\n");
printf(" -w INT set width to `INT', default=8\n");
printf(" -d CHAR delimit bits by `CHAR', default=\\040\n\n");
exit(exval);
}
/* print version and exit with exval */
void print_version(int exval) {
exit(exval);
}