我刚写了一个使用bzip2库API压缩文件的C函数。压缩不能正常工作。当我使用归档实用程序解压缩输出文件时,我获得了一些垃圾值以及实际数据。我按照bzip2库手册中的说明完成了所有操作。有人能告诉我出了什么问题吗?
代码可能结构不合理。这只是试图了解libzip2库的用法。
#define BUFSIZE 512
int main(int argc, char *argv[])
{
char file_name[64];
if(argc != 2)
{
printf("usage: compr <file name>");
return -1;
}
strncpy(file_name,argv[1],64);
return file_compress(file_name);
}
int file_compress(char * arg)
{
int input_fd, output_fd;
ssize_t ret_in ;
char buffer[BUFSIZE];
char buffout[BUFSIZE];
struct stat fileStat;
int insize;
int st;
bz_stream strm;
strm.bzalloc= NULL;
strm.bzfree= NULL;
strm.opaque= NULL;
st = BZ2_bzCompressInit (&strm,1,0,30 );
if(st != BZ_OK)
{
return 1;
}
else
{
input_fd = open (arg, O_RDONLY);
if (input_fd < 0)
{
return 1;
}
if(fstat(input_fd,&fileStat) < 0)
return 1;
insize = fileStat.st_size;
printf("File Size: \t%d bytes\n",insize);
strcat(arg,".bz2");
output_fd = open(arg, O_WRONLY | O_CREAT, 0644);
if(output_fd == -1)
{
return 1;
}
strm.avail_in = 0;
while(1)
{
if(insize > 0 && strm.avail_in == 0)
ret_in = read (input_fd, buffer, BUFSIZE);
else
ret_in = 0;
strm.next_in=buffer;
strm.avail_in=ret_in;
strm.next_out=buffout;
strm.avail_out=BUFSIZE;
if(insize == 0)
{
st= BZ2_bzCompress ( &strm,BZ_FINISH);
}
else if(insize <= BUFSIZE)
{
st= BZ2_bzCompress ( &strm,BZ_FINISH);
}
else
{
st=BZ2_bzCompress ( &strm,BZ_RUN);
}
insize -= ret_in;
if(BUFSIZE - strm.avail_out > 0)
{
int ret_out=write (output_fd, buffout, BUFSIZE - strm.avail_out);
printf("retout%d \n",ret_out);
}
if(st == BZ_STREAM_END)
break;
if(st < 0 )
{
return 1;
}
}
close (input_fd);
close (output_fd);
}
st = BZ2_bzCompressEnd (&strm );
if(st != BZ_OK)
{
// perror("ERROR BZ2_bzCompressEnd\n");
return 1;
}
return 0;
}