c语言写一个文件解压缩的程序
时间: 2023-06-24 09:05:21 浏览: 61
下面是一个简单的文件解压缩程序,使用 zlib 库实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#define CHUNK_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s <file.gz>\n", argv[0]);
return 1;
}
char *infile = argv[1];
char outfile[256];
strncpy(outfile, infile, strlen(infile) - 3);
outfile[strlen(infile) - 3] = '\0';
int ret;
unsigned have;
z_stream strm;
unsigned char in[CHUNK_SIZE];
unsigned char out[CHUNK_SIZE];
FILE *f_in = fopen(infile, "rb");
if (!f_in) {
printf("Failed to open input file %s\n", infile);
return 1;
}
FILE *f_out = fopen(outfile, "wb");
if (!f_out) {
printf("Failed to open output file %s\n", outfile);
fclose(f_in);
return 1;
}
memset(&strm, 0, sizeof(z_stream));
ret = inflateInit2(&strm, 15 + 32);
if (ret != Z_OK) {
printf("Failed to initialize inflate: %s\n", strm.msg);
fclose(f_in);
fclose(f_out);
return 1;
}
do {
strm.avail_in = fread(in, 1, CHUNK_SIZE, f_in);
if (strm.avail_in == 0) {
break;
}
strm.next_in = in;
do {
strm.avail_out = CHUNK_SIZE;
strm.next_out = out;
ret = inflate(&strm, Z_NO_FLUSH);
switch (ret) {
case Z_NEED_DICT:
case Z_DATA_ERROR:
case Z_MEM_ERROR:
printf("Failed to inflate: %s\n", strm.msg);
inflateEnd(&strm);
fclose(f_in);
fclose(f_out);
return 1;
}
have = CHUNK_SIZE - strm.avail_out;
fwrite(out, 1, have, f_out);
} while (strm.avail_out == 0);
} while (ret != Z_STREAM_END);
inflateEnd(&strm);
fclose(f_in);
fclose(f_out);
return 0;
}
```
程序的使用方法为:
```
$ ./unzip file.gz
```
其中 `file.gz` 是要解压缩的文件名。程序将解压缩后的文件保存在与输入文件同名的文件夹中,去除 `.gz` 后缀。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)