c primer plus 第13章,简单的文件压缩程序,把文件压缩成原来的1/3

/* reducto.c 把文件压缩成原来的1/3 */

#include<stdio.h>
#include<stdlib.h>   //exit() 原型 
#include<string.h>   //strcpy(),strcat() 原型 
#define LEN 40

int main(int grac,char *argv[])
{
	FILE *in,*out;   //声明指向file的指针 
	int ch;
	char name[LEN];   //存储输出文件名 
	int count = 0;
	if(grac<2)            //检查命令行参数 
	{
		fprintf(stderr,"Usage: %s filename\n",argv[0]);
		exit(EXIT_FAILURE);
	} 
	if((in=fopen(argv[1],"r")) ==NULL)   //设置输入 
	{
		fprintf(stderr,"I couldn't open the file \"%s\"\n",argv[1]);
		exit(EXIT_FAILURE);
	}
	strncpy(name,argv[1],LEN-5);  //LEN-5 为添加 ".red" 后缀名,预留空间 
	name[LEN-5]='\0';
	strcat(name,".red");   //拼接后缀名 
	if((out=fopen(name,"w")) ==NULL)   //以写模式打开name文件 
	{
		fprintf(stderr,"Can't create output file.\n");
		exit(3);
	}
	while((ch=getc(in)) !=EOF)
		if(count++ %3==0)     //打印3个字符中的第一个字符 
			putc(ch,out);      //把ch字符放入文件指针out 指向的文件中 
	if(fclose(in) !=0 || fclose(out) !=0)
		fprintf(stderr,"Error in closing files\n");
		
	return 0; 
}

运行程序

 压缩后的文件后缀名 .red

压缩后的内容见下图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值