/* 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
压缩后的内容见下图