编写一个程序,将一段文字写入磁盘文件《姓名》.dat保存起来。要求文件的第一部分保存文件的结构(含密钥的变形码),第二部分是文字用密钥加密的密文。文件被重新打开时要求输入密码并验证密码并限定密码的输入次数。
时间: 2024-03-19 14:44:51 浏览: 21
下面是一个简单的实现,实现了将文字写入磁盘文件并加密,以及重新打开文件并验证密码的功能。注意,由于考虑到安全性问题,这里使用了简单的加密算法,实际应用中需要考虑更加安全可靠的加密算法。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TRY 3 // 最大尝试密码次数
#define MAX_SIZE 1024 // 最大文件大小
// 加密函数
void encrypt(char *str, char key)
{
for (int i = 0; i < strlen(str); i++) {
str[i] ^= key; // 使用异或运算进行加密
}
}
// 写入文件函数
void write_file(char *filename, char *str, char key)
{
FILE *fp;
char buf[MAX_SIZE];
int len;
// 打开文件
if ((fp = fopen(filename, "wb")) == NULL) {
printf("Failed to open file %s\n", filename);
exit(1);
}
// 写入文件结构
buf[0] = key; // 记录密钥
fwrite(buf, sizeof(char), 1, fp);
// 加密并写入密文部分
encrypt(str, key);
len = strlen(str);
fwrite(str, sizeof(char), len, fp);
// 关闭文件
fclose(fp);
}
// 读取文件函数
char *read_file(char *filename)
{
FILE *fp;
char buf[MAX_SIZE];
char key;
char *str;
int len;
// 打开文件
if ((fp = fopen(filename, "rb")) == NULL) {
printf("Failed to open file %s\n", filename);
exit(1);
}
// 读取文件结构
fread(buf, sizeof(char), 1, fp);
key = buf[0];
// 读取密文部分并解密
fseek(fp, 0, SEEK_END);
len = ftell(fp) - 1;
str = (char *)malloc(sizeof(char) * (len + 1));
fseek(fp, 1, SEEK_SET);
fread(str, sizeof(char), len, fp);
str[len] = '\0';
encrypt(str, key);
// 关闭文件
fclose(fp);
return str;
}
int main()
{
char filename[20];
char input[100];
char *str;
char key;
int try_times = 0;
// 读取输入
printf("Input filename: ");
scanf("%s", filename);
printf("Input text: ");
scanf("%s", input);
// 随机生成密钥
srand((unsigned int)time(NULL));
key = rand() % 256;
// 写入文件
write_file(filename, input, key);
// 读取文件并验证密码
while (try_times < MAX_TRY) {
printf("Input password: ");
scanf("%hhd", &key);
str = read_file(filename);
if (str != NULL) {
printf("Text: %s\n", str);
free(str);
break;
} else {
printf("Invalid password! ");
try_times++;
if (try_times == MAX_TRY) {
printf("Reached maximum try times.\n");
} else {
printf("You have %d times left.\n", MAX_TRY - try_times);
}
}
}
return 0;
}
```
在这个程序中,首先用户需要输入文件名和要写入的文本,然后随机生成密钥并将文本加密后写入文件。在读取文件时,用户需要输入密码并验证,程序会使用输入的密码尝试解密文件内容,如果解密成功则输出文本内容,否则提示密码错误并重新输入。如果连续输入密码错误达到了最大次数,程序会自动退出。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)