C++对文本文件加密

编程入门 行业动态 更新时间:2024-10-28 16:17:52

引言:文本文件是指可以用记事本打开的文件,普通的txt文本,HTML文本BAT批处理文件.不包括word文档.


这里的思路是用fgetc() 函数每次从文件读取一个字符,而fputc()函数则可以每次向文件写入一个字符,利用该特性编写一个简单的文本加密器.


我们这里获得的可执行文件的位置,所以每次要把可执行文件和文本放在同一个目录下,每次加密完文件,会自动的把文本删除,转化为新的加密后的文本.


#include "stdio.h"
#include <stdlib.h>
#include <Windows.h>
#include "string.h"
int main()
{
	FILE *fp;
	FILE *temp;
	char ch;
	char strFileName[30];
	char strTempBuff[256];
	


	printf("Please Input File Name:");
	gets(strFileName);
	strFileName[29] = '\0';
	
	//GetModuleFileName(NULL,strTempBuff,sizeof(strTempBuff));
	GetCurrentDirectory(250,strTempBuff); //得到相对路径
	strcat(strTempBuff, "\\" );     //    "\\"是表示一个 \ 的意思

	strcat(strTempBuff,strFileName);
	//只读
	if ((fp = fopen(strTempBuff,"rb+")) == NULL)
	{
		printf("Open File %s Error!\n",strFileName);
		return -1;//

	}
	//写一个临时文件
	if ((temp = fopen("TempFile.pyp","wb+")) ==NULL)
	{
		printf("Create Tempoary File Error!\n");
		return -1;
	}
	//feof 文件末尾标志
	while(!feof(fp))
	{      
		ch = fgetc(fp);
		if ((int)ch!= -1&&(int)ch!= 0)
		{
			ch =~ch;
			fputc(ch,temp);
		}
	}
	fclose(temp);
	fclose(fp);
	//删除原文件
	sprintf(strTempBuff,"del %s",strFileName);
	system(strTempBuff);
	//将临时文件该为原文件名
	sprintf(strTempBuff,"ren TempFile.pyq %s",strFileName);
	system(strTempBuff); 
	printf("success!\n");
	return 0;
}


Tips: strcat(strTempBuff, "\\" ); 这里”\\” 是表示一条反斜杠的意思.



更多推荐

C++对文本文件加密

本文发布于:2023-06-14 03:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1434720.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件加密   文本

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!