【发布时间】:2016-02-08 15:57:55
【问题描述】:
我正在尝试在 C 中实现霍夫曼编码。我已经完成了树的构造,并随着算法的进行获得了每个符号的码字。但是现在我坚持将代码字插入到相应符号的二进制文件中。有人可以建议如何将代码字或二进制位写入二进制文件,以便我可以获得压缩文件。
码字的长度可变。
在文件中写入和读取这些位的函数会很有帮助。
这是我写的代码
void create_compressed_file()
{
char str[20],ch,*str2,str1[10],str_arr[6],str3[10];
FILE *fp,*fp2,*fp3;
int i,array[20],j=0;
fp2=fopen("newfile.txt","r"); // contains the original text file
fp3=fopen("codeword.txt","r"); // contains the symbol and codeword
while(fscanf(fp2,"%s",&str)==1)
{
rewind(fp3);
str2=strtok(str,"-");
while(str2!=NULL)
{
strcpy(str_arr,str2);
printf("str2= %s ",str_arr); //str2 stores the symbol(not char but a string)
printf(" %s-",str2);
while(fscanf(fp3,"%s",&str1)==1)
{
if(strcmp(str1,str_arr)==0)
{
fscanf(fp3,"%s",&str1); // extracted corresponding codeword(1s and 0s) of the symbol and stored it into str1
printf("%s\n",str1);
write_codeword_to_binaryfile(); // function that i want to create with is incomplete and need your help.
}
}
str2=strtok(NULL,"-");
rewind(fp3);
}
printf("\nspace:");
strcpy(str_arr,"space");
while(fscanf(fp3,"%s",&str1)==1)
{
if(strcmp(str1,str_arr)==0)
{
fscanf(fp3,"\n%s",&str1); // extract the codeword for(space)character
printf("%s\n",str1);
}
}
}
fclose(fp2);
fclose(fp3);
}
codeword.txt:
is 0000
por 00010
Plain 000110
most 0001110
the 0001111
ted 00100
text 00101
ly 0011000
near 0011001
pli 0011010
ap 0011011
ble 0011100
ta 0011101
by 0011110
sup 0011111
cryp 0100000
In 0100001
ra 0100010
tog 0100011
ting 0100100
tain 0100101
mands 0100110
com 0100111
mes 0101000
to 0101001
ge 0101010
sa 0101011
plain 0101100
phy 0101101
i tried the above code as below but it dint write anything...the file size after execution was 0 bytes:
#include<stdio.h>
#include<conio.h>
#include<stdint.h>
void write_codeword_to_binaryfile(
const char *codeword, // codeword to write, in ASCII format
FILE *file, // destination file
uint8_t *buffer,
int *fullness)
{
char c;
// fullness = ;
*buffer = 0;
for ( c = *codeword++; c != '\0'; c = *codeword++) // iterate
{
int bit = c - '0'; // convert from ASCII to binary 0/1
*buffer |= bit << (7 - fullness);
++fullness;
}
fputc(*buffer, file);
}
int main()
{
FILE *fp;
uint8_t *buffer=0;
char *c="10101010";
char b = 0;
int i;
fp=fopen("myfile.bin","wb");
write_codeword_to_binaryfile( c,fp,buffer, 8);
fclose(fp);
getch();
}
【问题讨论】:
-
您需要编写一个函数,将八位分组为一个字节并将其写入文件。
-
欢迎来到 Stack Overflow!请展示您的研究成果。请先阅读How to Ask页面。
-
检查
fread和fwrite。此外,通常的做法是编写一个新文件(您想要保留的内容可以复制到新文件中)并将您的内容添加到其中,但保持原始文件不变。这样做的原因是,如果编码不能以某种方式工作(糟糕的实现或其他),您将丢失文件的原始状态,因此您将无法清理您创建的混乱。如果您不需要原始文件,您可以在编码完成并验证工作后将其删除。 -
创建一个
bitwrite函数,该函数接受 1 位并将其转移到无符号静态缓冲区字节中。当字节“满”时,将其写入文件并重置字节缓冲区和位计数器。将每个霍夫曼代码的每一位传递给bitwrite函数。确保最后没有留下任何需要(移位?)并写入文件的“悬空”位。 -
显示你的一些代码。代码字是什么样的?
标签: c file-io bit-manipulation huffman-code