1 /* ------------------- huffc.c -------------------- */
6 extern struct DfHTree
*ht
;
9 static int lastchar
= '\n';
11 static void compress(FILE *, int, int);
12 static void outbit(FILE *fo
, int bit
);
14 static int fgetcx(FILE *fi
)
18 /* ------- bypass comments ------- */
19 if ((c
= fgetc(fi
)) == ';' && lastchar
== '\n')
21 while (c
!= '\n' && c
!= EOF
)
28 void main(int argc
, char *argv
[])
32 DF_BYTECOUNTER bytectr
= 0;
35 printf("\nusage: huffc infile outfile");
39 if ((fi
= fopen(argv
[1], "rb")) == NULL
) {
40 printf("\nCannot open %s", argv
[1]);
43 if ((fo
= fopen(argv
[2], "wb")) == NULL
) {
44 printf("\nCannot open %s", argv
[2]);
49 ht
= calloc(256, sizeof(struct DfHTree
));
51 /* - read the input file and count character frequency - */
52 while ((c
= fgetcx(fi
)) != EOF
) {
58 /* ---- build the huffman tree ---- */
61 /* --- write the byte count to the output file --- */
62 fwrite(&bytectr
, sizeof bytectr
, 1, fo
);
64 /* --- write the tree count to the output file --- */
65 fwrite(&treect
, sizeof treect
, 1, fo
);
67 /* --- write the root offset to the output file --- */
68 fwrite(&root
, sizeof root
, 1, fo
);
70 /* -- write the tree to the output file -- */
71 for (c
= 256; c
< treect
; c
++) {
74 fwrite(&lf
, sizeof lf
, 1, fo
);
75 fwrite(&rt
, sizeof rt
, 1, fo
);
78 /* ------ compress the file ------ */
80 while ((c
= fgetcx(fi
)) != EOF
)
81 compress(fo
, (c
& 255), 0);
89 /* ---- compress a character value into a bit stream ---- */
90 static void compress(FILE *fo
, int h
, int child
)
92 if (ht
[h
].parent
!= -1)
93 compress(fo
, ht
[h
].parent
, h
);
95 if (child
== ht
[h
].right
)
97 else if (child
== ht
[h
].left
)
105 /* -- collect and write bits to the compressed output file -- */
106 static void outbit(FILE *fo
, int bit
)
108 if (ct8
== 8 || bit
== -1) {
116 out8
= (out8
<< 1) | bit
;