文件读写和加解密
为了实现以下功能,大侠们帮忙看看我的程序需要咋改,怎么实现加解密数据后写入文件,求给改改程序中。。。。。。。。。。..............................不胜感谢!!!!功能:
输入一数据文件和密码,输出对应的加/解密数据文件。读取数据文件,利用异或运算对数据文件内容逐字节进行加/解密运算;将加/解密后的数据写入给定的数据文件
程序:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
void encryption(char *str)
{
int i=0,key;
char fname[20],c,ch=45;
FILE *fp;
printf("输入要加密文件的路径\n");
scanf("%s", fname);
printf("请输入密钥\n");
scanf("%d",&key);
if( (fp = fopen(fname,"r+")) ==NULL)
{
printf("error");
exit(0);
}
while( (c = fgetc(fp)) != EOF)
{
c = c^ch;
str[i] = c;
i++;
}
str[i]='\0';
printf("%s\n", str);
fclose(fp);
}
void decrypt()
{
int i=0,key;
char str[MAX],fname[20],c,ch=45;
FILE *fp;
printf("输入要解密文件的路径\n");
scanf("%s", fname);
printf("请输入密钥\n");
scanf("%d",&key);
if( (fp = fopen(fname,"r+")) ==NULL)
{
printf("error");
exit(0);
}
while( (c = fgetc(fp)) != EOF)
{
c = c^ch;
str[i] = c;
i++;
}
str[i]='\0';
printf("%s\n", str);
fclose(fp);
}
void menu()
{
printf("\n1.Encrypt the file");
printf("\n2.Decrypt the file");
printf("\n3.Quit\n");
}
void main(int argc,char **argv)
{
char i_num[3000],o_num[3000];
FILE *infp=NULL;
FILE *outfp=NULL;
FILE *fp=NULL;
int i;
int c,num;
{
if(argc!=3)
printf("输入错误!");
else
printf("本次操作是将文件里的字符修改排版;\n把空格排版改为','每两排换行改为';'\n\n");
infp=fopen(argv[1],"w");
outfp=fopen(argv[2],"w");
printf("成功打开%s;%s!\n",argv[1],argv[2]);
printf("输入要写入%s的字符串,并以*回车结束:\n",argv[1]);
for(i=0;;i++)//fgets(i_num,sizeof(i_num),infp);标准输入
{
scanf("%c",&i_num[i]);
if(i_num[i]=='*')
{
i_num[i]='\0';
break;
}
}
fputs(i_num,infp);
printf("成功写入%s!\n\n",argv[1]);
fclose(infp);
}
fp=fopen(argv[1],"r");
i=0;
while((c=fgetc(fp))!=EOF)
{
if(c==' ')
{
c=',';
fputc(c,outfp);
}
else if(c=='\n')
{
i++;
if(i%2!=0)
{
c=';';
fputc(c,outfp);
}
else
fputc(c,outfp);
}
else
fputc(c,outfp);
}
printf("成功转换输入到%s中!\n",argv[2]);
fclose(outfp);
printf("成功关闭文件!\n\n");
printf("本次操作成功!请查看文件!\n");
switch(num)
{
case 1:encryption();break;
case 2:decrypt();break;
default:break;
}
}