本篇文章为大家展示了使用C语言怎么加密解密文件,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
//#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<time.h>
#include<sys/stat.h>
#pragma warning(disable:4996)
//加密
void Encryption(char *p, size_t n)
{
for (int i = 0; i < n;++i)
{
*p += 7;
}
}
//解密
void Decrypt(char *p, size_t n)
{
for (int i = 0; i < n;++i)
{
*p -= 7;
}
}
char *EnOrDe = {0};
int main(int argc, char *args[])
{
clock_t c1 = clock();//系统当前时间,毫秒为单位
char *FileNameSrc = (char *)calloc(160, sizeof(char));//待操作文件
char *p2 = (char *)calloc(200, sizeof(char));//操作后文件名
//从命令行获取文件名和要处理的操作
FileNameSrc = args[1];//文件名,包含路径
char *p1 = args[1];
EnOrDe = args[2];//en表示加密,de表示解密
/*FileNameSrc = "E:\\iPhone6-new.txt" ;
char *p1 = FileNameSrc;
EnOrDe = "de";*/
/**********处理生成新的文件名***********/
//char *p2 = { 0 };
/*FileNameSrc = p1;*/
//printf("%s\n", FileNameSrc);
//printf("%s\n", EnOrDe);
int index = 0;
while (*p1)
{
if (*p1!='.')
{
*p2 = *p1;
p2++;
p1++;
index++;
}
else if (*p1 == '.')
{
*p2 = '_';
p2++;
*p2 = 'H';
p2++;
*p2 = '.';
p2++;
p1++;
index+=2;
}
}
printf("\n");
printf("信息摘要:\n");
printf("--------------------------------------\n");
printf("原文件:%s\n", FileNameSrc);
printf("操作:%s (en——加密,de——解密)\n", EnOrDe);
printf("预计结果文件:%s\n", p2 - index - 1);
printf("--------------------------------------\n\n");
printf("请稍后,玩命处理中......\n");
char *FileNameDst = p2 - index - 1;
FILE *pr = fopen(FileNameSrc, "rb");
FILE *pw = fopen(FileNameDst, "wb");
struct stat st = { 0 };
size_t fileSize = st.st_size;//以字节为单位
//char *buf = NULL;
//if (fileSize<1024*1024)//小于1M
//{
// buf = malloc(sizeof(char) * 1024 * 20);//分配20K
//}
//else
//{
// buf = malloc(sizeof(char)*fileSize / 10);
//}
char *buf = calloc(1024 * 1024 * 25, sizeof(int));//分配100M
/*************定义函数指针***************/
void(*pFunc)(char *, size_t);
pFunc = NULL;
if (strcmp(EnOrDe, "en") == 0)
{
pFunc = Encryption;
}
else if (strcmp(EnOrDe, "de") == 0)
{
pFunc = Decrypt;
}
/*************定义函数指针***************/
while (!feof(pr))
{
//memset(buf, 0, sizeof(buf));//calloc自动初始化为0
size_t res = fread(buf, sizeof(char), sizeof(buf), pr);
pFunc(buf, res);
fwrite(buf, sizeof(char), res, pw);
}
fclose(pr);
fclose(pw);
printf("\n");
printf("--------------------------------------\n");
printf("执行成功!\n所在目录:%s\n", FileNameDst);
clock_t c2 = clock();//系统当前时间,毫秒为单位
printf("耗时:%u毫秒\n", c2-c1);
printf("--------------------------------------\n");
return 0;
}
效果:
上述内容就是使用C语言怎么加密解密文件,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。