سورس كود لبرنامج ضغط وفك ضغط (برنامج بسيط )
#include<stdio.h>#include<stdlib.h>#include<string.h>#include<io.h>#include<conio.h>#include<ctype.h>#define HEADER "PAC"void my_strcpy_rev(char *s,const char (*d)[20],int i){ int k=0; char *p; p=(char*)d+(i*20); while(p[k]){ s[k]=p[k]; k++; } s[k]=p[k]; }void my_strcpy(char (*d)[20],const char *s,int i){ int k=0; char *p; p=(char*)d+(i*20); while(s[k]){ p[k]=s[k]; k++; } p[k]=s[k]; }struct p{char header[4];int num_offiles;long sizes[10];char names[10][20];char delim[4];}*pack;char *g_names[10];/* *pack -p file1 file2 file3 -d dest *pack -up file*/int main(int argc,char **argv){int lpr;FILE *file;int fno;if(argc<3){ printf("Syntax:\nFor packing\n\tpackin -p file1 file2 file3 ... -d dest\nFor unpacking\n\tpackin -up file"); exit(0); }pack=(struct p*)malloc(sizeof(struct p));for(lpr=1;lpr<argc;lpr++){ if(!strcmp(argv[lpr],"-p")){ strcpy(pack->header,HEADER); strcpy(pack->delim,"OOO"); pack->num_offiles=argc-4; int i=0; lpr++; while(strcmp(argv[lpr],"-d")){ g_names=(char*)malloc(strlen(argv[lpr])+1); my_strcpy(pack->names,argv[lpr],i); strcpy(g_names,argv[lpr]); file=fopen(argv[lpr],"rb"); if(!file){ printf("Error reading file!"); exit(0); } fno=fileno(file); pack->sizes=lseek(fno,(long)0,SEEK_END); fclose(file); i++; lpr++; } lpr++; FILE *file,*dest; int ch; dest=fopen(argv[lpr],"ab"); if(!dest){ printf("Error writing file"); exit(0); } fwrite((struct p*)pack,sizeof(struct p),1,dest); fclose(dest); int handle; for(i=0;i<pack->num_offiles;i++){ dest=fopen(argv[lpr],"ab"); handle=fileno(dest); lseek(handle,0,SEEK_END); if(!dest){ printf("Error writing file"); exit(0); } file=fopen(g_names,"rb"); if(!file){ printf("Error reading file"); exit(0); } ch=getc(file); while(ch!=EOF){ putc(ch,dest); ch=getc(file); } fclose(file); fclose(dest); } printf(" ... FIN"); fclose(dest); exit(0); } else if(!strcmp(argv[lpr],"-up")){ printf("\nwait ... "); lpr++; FILE *file,*dest; pack=(struct p*)malloc(sizeof(struct p)); file=fopen(argv[lpr],"rb"); if(!file){ printf("\nError reading file"); exit(0); } fread((struct p*)pack,sizeof(struct p),1,file); if(strcmp(pack->header,HEADER)){ printf("\nIncompatible format"); exit(0); } char dname[20]; long dsize; int ch; for(int i=0;i<pack->num_offiles;i++){ my_strcpy_rev(dname,pack->names,i); dest=fopen(dname,"wb"); if(!dest){ printf("\nError writing"); exit(0); } long count=0; while(count<pack->sizes){ ch=getc(file); putc(ch,dest); count++; } fclose(dest); } printf("%d files retrieved",pack->num_offiles); exit(0); } else{ printf("Syntax:\nFor packing\n\tpack -p file1 file2 file3 ... dest\nFor unpacking\n\tpack -up file dest"); exit(0); } }}
