程序代码:
#include<stdio.h>
#include<stdlib.h>
typedef char ElemType ;
/*
** 读入明文或者密文,读入缓冲区
*/
int openSourFile( ElemType **buffer)
{
FILE *myfile_src;
ElemType filename[20];
printf("please input the filename :\n");
scanf("%s",filename);
long file_size;
if((myfile_src=fopen(filename,"rb"))==NULL)
{
return 0;
}
fseek(myfile_src,0,SEEK_END);
file_size=ftell(myfile_src);
fseek(myfile_src,0,SEEK_SET);
printf("文件的长度是:\n");
printf("%ld\n",file_size);
*buffer=(ElemType *)malloc(file_size);
fread(*buffer,1,file_size,myfile_src);
fclose(myfile_src);
return file_size;
}
/*
**文件加密
*/
void encryption( ElemType buffer[],long file_size,int key)
{
int i;
for(i=0;i<file_size;i++)
{
buffer[i]=buffer[i]+key;
}
}
/*
**文件解密
*/
void decryption( ElemType buffer[],long file_size,int key)
{
int i;
for(i=0;i<file_size;i++)
{
buffer[i]=buffer[i]-key;
}
}
/*
** 保存文件,用来读入明文,或者保存密文
*/
void saveDesrFile( ElemType *buffer,long file_size)
{
FILE *file_dst;
ElemType filename[20];
printf("Please input the path and filename of the file that you want have processed\n");
scanf("%s",filename);
getchar();
if(!(file_dst=fopen(filename,"wb")))
{
printf("ERROR!\n");
}
fwrite(buffer,1,file_size,file_dst);
printf("OK!\n");
fclose(file_dst);
}
void Process(int a)
{
ElemType *buffer;
int key;
long file_size;
//buffer=(unsigned char *)malloc(1);//这里的N是几都可以,因为在函数中又重新开辟空间了,为了节省空间这里最好是1
file_size=openSourFile(&buffer);
printf("Please input the key (a integer) for encryption or decryption\n");
scanf("%d",&key);
if(a==0)
{
encryption(buffer,file_size,key);
}
else
{
decryption(buffer,file_size,key);
}
saveDesrFile(buffer,file_size);
}
void menu()
{
printf("**************************************************************\n");
printf("==========A SIMPLE ENCRYPTION OR DECRYPTION SYSTEM==========\n");
printf(" ENCRYPTION press 'E' DECRYPTION press 'D' QUIT press 'Q'\n");
printf("**************************************************************\n");
}
int main()
{
ElemType flag;
menu();
flag=getchar();
getchar();
while(flag!='Q')
{
switch(flag)
{
case 'E':
Process(0);break;
case 'D':
Process(1);break;
default:printf("Input error!\n");break;
}
printf("这一步已经完成,请换下一步操作!\n");
flag=getchar();
getchar();
}
return 0;
}//实现创建个文件,里边写上明文,不用我说了吧
还好哥的家底还算殷实~·