C语言将一个简单的文件压缩

本文介绍了使用C语言如何将简单文件进行压缩处理。通过对比fprintf()与printf()的相似性,强调在处理错误信息时,通常会利用stderr将错误信息输出到标准错误文件中,遵循C语言的标准实践。
摘要由CSDN通过智能技术生成

#include <stdio.h>
#include <stdlib.h>                       /* 为了调用exit() */
#include <string.h>                         /*使用strcpy()和strcat()*/


#define LEN 40
int main(int argc,char *argv[])
{
    FILE *in,*out;                           //声明连个FILE指针
    int ch;
    char name[LEN];                             //用于存储输入文件名
    int count = 0;
    //检查命令行参数
    if(argc < 2)
    {
        fprintf(stderr,"Usage: %s filename\n",argv[0]);
        exit(1);
    }
    //实现文件输入
    if((in = fopen(argv[1],"r")) == NULL)
    {
        fprintf(stderr,"I couldn't open the file \"%s\"\n",argv[1]);
        exit(2);
    }
    //实
下面是一个简单文件压缩程序,使用 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` 后缀。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

道亦无名

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值