c语言文件加密和解密方法如下:
1、首先打开VC++6.0;
2、选择文件,新建;
3、选择C++sourcefile新建一个空白文档;
4、声明头文件
#include
#include
#include
首先写个加密函数,算法就是简介里说的;
{
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);
}
}
写解密子函数:与加密的过程相反;
{
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;
}