C语言对文本内数据加解密测试

正如题目,本篇博客是对文本(orl.txt)内容进行加密输入到加密文本(encrypt.txt)内,再将加密文本(encrypt.txt)内的密文解密到明文文本(decrypt.txt)内的一个加密解密测试,其中借鉴了专家韩曙亮的博客:

【C 语言】文件操作 ( 读文本文件 | 文本加密解密 | fgets 函数 | fputs 函数 )

好,废话不多说,直接上源码。

#include<stdio.h>
#include<string.h>

void encode(char* s);
void decode(char* s);
  
int main() {
    //初始化数组,一会儿存放数据用
    char s[1024] = { 0 };
    //初始化两个变量
    int i = 0;
    int j = 0;
    //加入循环防止orl.txt文本内容被读取加密并写入encrypt.txt后程序结束
    while(i <= 1) {
        //加入if()else语句分别对orl.txt、enrypt.txt、derycpt.txt进行操作
        if (j == 0) {
            //两个文件指针,然后用fopen_s对文本文件进行打开操作
            FILE* p;
            errno_t err = fopen_s(&p, "C:/Users/Administrator/Desktop/orl.txt", "r");
            FILE* p2;
            errno_t err2 = fopen_s(&p2, "C:/Users/Administrator/Desktop/encrypt.txt", "w");
            //判断文件orl.txt内是否为空
            while (!feof(p))
            {
                //对数组 s 进行初始化
                memset(s, 0, sizeof(s));
                //将orl.txt的文本内容写入数组中
                fgets(s, sizeof(s), p);
                //通过encode()函数,对数组内容进行遍历加密
                encode(s);
                //将加密后的数组内容写入到encrypt.txt中
                fputs(s, p2);
                printf("%s", s);
            }
            //关闭orl.txt和encrypt.txt
            fclose(p);
            fclose(p2);
            j++;
        }
        //else部分操作和if部分操作一样
        else
        {
            FILE* p3;
            errno_t err3 = fopen_s(&p3, "C:/Users/Administrator/Desktop/encrypt.txt", "r");
            FILE* p4;
            errno_t err4 = fopen_s(&p4, "C:/Users/Administrator/Desktop/decrypt.txt", "w");
            
            while (!feof(p3))
            {
                memset(s, 0, sizeof(s));
                fgets(s, sizeof(s), p3);
                decode(s);
                fputs(s, p4);
                printf("%s", s);
            }
            fclose(p3);
            fclose(p4);
            break;
        }
        i++;
    }
    
    printf("success");

    return 0;
}

void encode(char* s) {
    while (*s)
    {
        (*s)++;
        s++;
    }
}
void decode(char* s) {
    while (*s)
    {
        (*s)--;
        s++;
    }
}

测试:

猜你喜欢

转载自blog.csdn.net/qq_46230392/article/details/129687559