C 语言实现的哈夫曼编码压缩算法
"FILE* ifp, * ofp; //输入文件指针,输出文件指针\nchar inputfile[100], outputfile[100];\nunsigned char c;\nint i, j, f, n, m;\nint pt1;\nchar buf[MAX];\nHuffmanTreeNode header[MAX];\nint length1, length2;\ndouble divx;\n\n//压缩函数\nvoid compress() {\n\n\t//打开输入文件\n\tprintf("\t请输入要压缩的文件名:");\n\tscanf("%s", inputfile);\n\tinputfile[strlen(inputfile)] = '\0'; // 在字符串末尾添加 '\0' 终止符\n\tifp = fopen(inputfile, "rb");//以二进制方式打开输入文件\n\tif (ifp == NULL) {\n\t\tprintf("\t打开文件失败\n");\n\t\treturn;\n\t}\n\n\t//统计字符出现次数\n\tfseek(ifp, 0, SEEK_END);\n\tlength1 = ftell(ifp); //文件长度\n\tfseek(ifp, 0, SEEK_SET);\n\tfor (i = 0; i < MAX; i++) {\n\t\theader[i].count = 0;\n\t\theader[i].parent = -1;\n\t\theader[i].lch = -1;\n\t\theader[i].rch = -1;\n\t\theader[i].b = (unsigned char)i;\n\t}\n\twhile (!feof(ifp)) {\n\t\tc = fgetc(ifp);\n\t\theader[c].count++;\n\t}\n\t//构建哈夫曼树\n\tn = 0;\n\tfor (i = 0; i < MAX; i++) {\n\t\tif (header[i].count == 0)\n\t\t\tcontinue;\n\t\tn++;\n\t}\n\tm = 2 * n - 1;\n\tfor (i = n; i < m; i++)\n\t{\n\t\tint min1 = 9999999;//最小权值初值\n\t\tfor (j = 0; j < i; j++) {\n\t\t\tif (header[j].parent != -1)\n\t\t\t\tcontinue;\n\t\t\t/parent!=-1说明该结点已存在哈夫曼\n\t\t\t树中,跳出循环重新选择新结点/\n\t\t\tif (min1 > header[j].count) {\n\t\t\t\tpt1 = j;\n\t\t\t\tmin1 = header[j].count;\n\t\t\t}\n\t\t}\n\t\theader[i].count = header[pt1].count;\n\t\theader[pt1].parent = i;\n\t\theader[i].lch = pt1;\n\n\t\tmin1 = 999999999;\n\t\tfor (j = 0; j < i; j++) {\n\t\t\tif (header[j].parent != -1)\n\t\t\t\tcontinue;\n\t\t\tif (min1 > header[j].count) {\n\t\t\t\tpt1 = j;\n\t\t\t\tmin1 = header[j].count;\n\t\t\t}\n\t\t}\n\n\t\theader[i].count += header[pt1].count;\n\t\theader[i].rch = pt1;\n\t\theader[pt1].parent = i;\n\t}\n\n}
原文地址: https://www.cveoy.top/t/topic/pwMV 著作权归作者所有。请勿转载和采集!