其他分享
首页 > 其他分享> > C语言代码实现简单的加密、解密文件

C语言代码实现简单的加密、解密文件

作者:互联网

代码如下:

#include<stdlib.h>
#include <stdio.h>
#pragma warning(disable : 4996)
 
int getfilesize(char *path)
{
    FILE *pf = fopen(path, "r");
    if (pf == NULL)
    {
        return -1;
    }
    else
    {
        fseek(pf, 0, SEEK_END);
        int length = ftell(pf);
        return length;
    }
}
/*
void copy(char *oldpath, char *newpath)
{
    FILE *pfr, *pfw;
    pfr = fopen(oldpath, "rb");
    pfw = fopen(newpath, "wb");
    if (pfr == NULL || pfw == NULL)
    {
        fclose(pfr);
        fclose(pfw);
        return;
    }
    else
    {
        int length = getfilesize(oldpath);
        char *p = (char *)malloc(length*sizeof(char));
        fread(p, sizeof(char), length, pfr);
        fwrite(p, sizeof(char), length, pfw);
        fclose(pfr);
        fclose(pfw);
    }
}
*/
void EncryptFile(char *oldpath, char *newpath)
{
    int i = 0;
    FILE *pfr, *pfw;
    pfr = fopen(oldpath, "rb");
    pfw = fopen(newpath, "wb");
    if (pfr == NULL || pfw == NULL)
    {
        fclose(pfr);
        fclose(pfw);
        return;
    }
    else
    {
        int length = getfilesize(oldpath);
        char *p = (char *)malloc(length*sizeof(char));
        fread(p, sizeof(char), length, pfr);
        for (i = 0; i < length; i++)
        {
            p[i] ^= 'A';
        }
        fwrite(p, sizeof(char), length, pfw);
        fclose(pfr);
        fclose(pfw);
    }
}
 
void DecryptFile(char *oldpath, char *newpath)
{
    int i = 0;
    FILE *pfr, *pfw;
    pfr = fopen(oldpath, "rb");
    pfw = fopen(newpath, "wb");
    if (pfr == NULL || pfw == NULL)
    {
        fclose(pfr);
        fclose(pfw);
        return;
    }
    else
    {
        int length = getfilesize(oldpath);
        char *p = (char *)malloc(length*sizeof(char));
        fread(p, sizeof(char), length, pfr);
        for (i = 0; i < length; i++)
        {
            p[i] ^= 'A';
        }
        fwrite(p, sizeof(char), length, pfw);
        fclose(pfr);
        fclose(pfw);
    }
}
 
void main()
{          
	// 原始文件的路径
    char *oldpath = "tmAppAbDBB.db";
    // 加密后的路径
    char *newpath = "aa.db";
    // 解密后的路径
    char *newDecryptFilepath = "cc.db";
    EncryptFile(oldpath, newpath);
    DecryptFile(newpath, newDecryptFilepath);
}

标签:加密,fclose,解密,C语言,char,length,pfr,oldpath,pfw
来源: https://blog.csdn.net/sexyluna/article/details/114004990