文件加密解密小程序

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


int process(char *filename, char *opration);
int read_file(char *filename, char **buf);
int write_file(char *buf, long file_size);
int decode(char *buf, int file_size, int key);
int encrypt(char *buf, int file_size, int key);

int main(int argc, char **argv)
{
	char flag;

	if (argc != 3)
	 {
		printf("error!the type is :%s <filename> <opration>\n", argv[0]);
		exit(-1);
	 }

	if ((*argv[2] == 'e') || (*argv[2] == 'd'))
	  process(argv[1], argv[2]);
	else
	 {
		printf("error:opration only be e(encrypt) or d(decode)\n");
		exit(-1);
	 }

	return 0;
}

int process(char *filename, char *opration)
{
	FILE *myfile_dst;
	char *buf;
	int key = 123;
	long file_size;

	file_size = read_file(filename, &buf);

	if (*opration == 'e')
	  encrypt(buf, file_size, key);
	else if(*opration == 'd') 
	  decode(buf, file_size, key);

	write_file(buf, file_size);

	return 0;
}

int read_file(char *filename, char **buf)
{
	FILE *myfile_src;
	long file_size;

	if (!(myfile_src = fopen(filename, "r")))
	 {
		perror("fopen");
	 }

	fseek(myfile_src, 0, SEEK_END);
	file_size = ftell(myfile_src);
	fseek(myfile_src, 0, SEEK_SET);

	*buf = (char *)malloc(file_size);
	fread(*buf, 1, file_size, myfile_src);
	fclose(myfile_src);

	return file_size;
}

int write_file(char *buf, long file_size)
{
	FILE *myfile_dst;
	char filename[20];

	printf("please input the file name that you want to save:\n");
	scanf("%s", filename);
	if (!(myfile_dst = fopen(filename, "wb")))
	 {
		perror("fopen");
	 }
	fwrite(buf, 1, file_size, myfile_dst);
	printf(">>>>>>>>>>>>>>%s is save<<<<<<<<<<<<<<<\n", filename);
	fclose(myfile_dst);

	return 0;
}

int encrypt(char buf[], int file_size, int key)
{
	int i;

	for(i = 0; i < file_size; i ++)
	  buf[i] = buf[i] + key;
	
	return 0;
}

int decode(char *buf, int file_size, int key)
{
	int i;
	
	for(i = 0; i < file_size; i ++)
	  buf[i] = buf[i] - key;
	
	return 0;
}

非常简单的文件加密解密,有很多缺陷需要修改,以后慢慢增加
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值