跪求c語言編程問題文件移位加密與解密急?
c語言文件加密和解密方法如下:
1、首先打開VC++6.0;
2、選擇文件,新建;
3、選擇C++sourceFILE新建一個空白文檔;
4、聲明頭文件
#include
#include
#include
首先寫個加密函數,算法就是簡介里說的;
void?EncryptFile(file?*sfp,FILE?*dfp,char?pwd)
{
char?ch;
if(sfp==0||dfp==0)
{
printf("ERROR!\n");
return;
}
while((ch=fgetc(sfp))!=EOF)
{
if((ch>='a')&&(ch
{
ch=(ch-'a'+1)%26+'a';
ch=ch^pwd;
}
if((ch>='A')&&(ch
{
ch=(ch-'A'+1)%26+'A';
ch=ch^pwd;
}
fputc(ch,dfp);
}
}
寫解密子函數:與加密的過程相反;
void?DecryptFile(FILE?*sfp,FILE?*dfp,char?pwd)
{
char?ch;
while((ch=fgetc(sfp))!=EOF)
{
if((ch>='a')&&(ch
{
ch=ch^pwd;
ch=(ch-'a'+25)%26+'a';
}
if((ch>='A')&&(ch
{
ch=ch^pwd;
ch=(ch-'A'+25)%26+'A';
}
fputc(ch,dfp);
}
}
輸出函數,輸出文件內容
void?OutputFile(FILE?*fp)
{
char?ch;
while((ch=fgetc(fp))!=EOF)
putchar(ch);
}
主函數,主要調用這幾個函數
int?main()
{
/*用戶輸入的要加密的文件名*/
char?sfilename[20];
/*用戶輸入加密后保存的文件名*/
char?dfilename[20];
/*用來保存密碼字符*/
char?pwd;
FILE?*sfp,*dfp;
printf("\nPlease?input?filename?to?be?encrypted:\n");
/*得到要加密的文件名*/
gets(sfilename);
/*得到加密后你要的文件名*/
printf("input?filename?to?save?the?encrypted?file:\n");
gets(dfilename);
/*得到加密字符*/
printf("Please?input?your?Password:\n");
//scanf("%c",&pwd);
pwd=getch();
/*屏幕以*來表示輸入的加密字符*/
printf("*\n");
/*以只讀方式打開要加密的文件*/
if((sfp=fopen(sfilename,"r"))==0)
{
printf("Can't?open?the?file?:%s\n",sfilename);
exit(0);
}
/*輸出要加密的文件*/
printf("\nThe?the?text?of?file?to?be?encrypted?is:\n");
OutputFile(sfp);
/*建立加密后的文件*/
if((dfp=fopen(dfilename,"w+"))==0)
{
printf("Can't?open?or?create?the?file?:%s\n",dfilename);
//exit(0);
}
/*文件加密*/
fseek(sfp,0L,SEEK_SET);
EncryptFile(sfp,dfp,pwd);
printf("\n\nEncrypted?the?file?successfully!\n");
/*輸出加密后的文件*/
printf("\nAfter?encrypting?the?text?of?file?is:\n");
fseek(dfp,0L,SEEK_SET);
OutputFile(dfp);
fclose(sfp);
fclose(dfp);
getch();
return?0;
}