文本加密算法是将字母表中的字母向后移动一定位置而实现,其中26个字母循环使用,z的后面可以看成是a。 例如,当密钥为k = 3,即向后移动3位。
请编写一个程序,可以把一段文字进行加密。
程序从文本文件word.txt中读取一段文本"Go ahead, this morning!",运行程序进行加密处理,输出加密之后的文本,并把该加密文本存入另一个文本文件password.txt中。
这样?
#include <stdio.h>
#include <stdlib.h>
#define KEY 3 // 加密密钥,向后移动3位
int main()
{
FILE *fp1, *fp2;
char ch;
// 打开要读取的文件
fp1 = fopen("word.txt", "r");
if (fp1 == NULL)
{
printf("无法打开文件\n");
exit(1);
}
// 打开要写入的文件
fp2 = fopen("password.txt", "w");
if (fp2 == NULL)
{
printf("无法打开文件\n");
exit(1);
}
// 读取文件内容并加密
while ((ch = fgetc(fp1)) != EOF)
{
if (ch >= 'a' && ch <= 'z')
{
ch = (ch - 'a' + KEY) % 26 + 'a'; // 加密小写字母
}
else if (ch >= 'A' && ch <= 'Z')
{
ch = (ch - 'A' + KEY) % 26 + 'A'; // 加密大写字母
}
fputc(ch, fp2); // 将加密后的字符写入文件
}
// 关闭文件
fclose(fp1);
fclose(fp2);
printf("加密成功!\n");
return 0;
}
以下是一个引用GPT的解决方案:
#include <stdio.h>
#include <stdlib.h>
// 将字符c向后移动k位,返回加密后的字符
char encrypt(char c, int k) {
if (c >= 'a' && c <= 'z') {
return ((c - 'a' + k) % 26 + 'a');
} else if (c >= 'A' && c <= 'Z') {
return ((c - 'A' + k) % 26 + 'A');
} else {
return c; // 非字母字符不加密
}
}
int main() {
int k = 3; // 加密密钥
// 打开输入文件
FILE* input_file = fopen("word.txt", "r");
if (input_file == NULL) {
perror("Failed to open input file");
exit(EXIT_FAILURE);
}
// 打开输出文件
FILE* output_file = fopen("password.txt", "w");
if (output_file == NULL) {
perror("Failed to open output file");
exit(EXIT_FAILURE);
}
// 加密输入文件中的文本并输出到输出文件
int c;
while ((c = getc(input_file)) != EOF) {
char e = encrypt(c, k);
fputc(e, stdout);
fputc(e, output_file);
}
// 关闭文件
fclose(input_file);
fclose(output_file);
return 0;
}
解释一下主要思路:
encrypt
函数实现了加密的算法。对于每个输入的字符,如果它是小写字母,则将其转换为0~25之间的数字,加上密钥k,再取余26得到新的数字,最后转换回字母;如果是大写字母,同样的操作只是加上的数字要多一个偏移,即'A'-'a'=32。fopen
和 fclose
函数。getc
函数读取输入文件中的字符,用 fputc
函数输出到标准输出和输出文件中,同时也调用了 encrypt
函数进行加密。