C实现简单文本加解密

这里我们用C语言实现一个简单的文本加解密小工具。

实现代码如下所示:

 1 /*
 2     filename: encrypt.c
 3 */
 4 #include <stdio.h>
 5 #include <stdlib.h>
 6 
 7 #define MAX 256
 8 
 9 int main(void)
10 {
11     FILE * fp;
12     FILE * ftemp;
13     char ch;
14     char strFileName[MAX];
15     char strTempBuff[MAX];
16 
17     printf("please input the file name:");
18     gets(strFileName); //输入待加密文件名
19 
20     if (NULL == (fp=fopen(strFileName, "rb"))) //以只读方式打开文件
21     {
22         printf("failed to open file.\n");
23         return -1;
24     }
25 
26     if (NULL == (ftemp=fopen("tempfile.data", "wb"))) //创建一个临时文件
27     {
28         printf("creating tempfile failed.\n");
29         return -1;
30     }
31 
32     while ( !feof(fp) ) //feof()未到文件尾返回0
33     {
34         ch = fgetc(fp);
35         if ( (int)ch != -1 && (int)ch != 0 ) //EOF and '\0'
36         {
37             ch = ~ch; //将其取反
38             fputc(ch, ftemp); //写入到临时文件
39         }
40     }
41     fclose(ftemp);
42     fclose(fp);
43 
44     /* 删除原文件 */
45     sprintf(strTempBuff, "del %s", strFileName);
46     system(strTempBuff);
47 
48     /* 将临时文件名改为原文件名 */
49     sprintf(strTempBuff, "ren tempfile.data %s", strFileName);
50     system(strTempBuff);
51 
52     return 0;
53 }

 

posted @ 2013-09-28 13:53  unfickleness  阅读(319)  评论(0编辑  收藏  举报