键盘输入一篇英文日记(若干行若干段落),将其按规律译成密码存储到磁盘文件Diary.txt中,再从该文件中读取这些密文输出到显示器。密码规律:A-Z,B-Y,C-X, ……,a-z,b-y,c-x,…… 非字母字符则不变。
参考代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX_INPUT_LENGTH 100000
void encrypt(char* input, char* output);
void decrypt(char* input, char* output);
int main() {
char input[MAX_INPUT_LENGTH];
char encrypted[MAX_INPUT_LENGTH];
char decrypted[MAX_INPUT_LENGTH];
char filename[] = "Diary.txt";
// 读取键盘输入
printf("请输入一篇英文日记:\n");
fgets(input, MAX_INPUT_LENGTH, stdin);
input[strcspn(input, "\n")] = '\0'; // 去除fgets读取字符串时末尾自带的换行符
// 加密并写入文件
encrypt(input, encrypted);
FILE* fp = fopen(filename, "w");
if (fp == NULL) {
printf("无法打开文件 %s 进行写入。\n", filename);
return 1;
}
fputs(encrypted, fp);
fclose(fp);
printf("已将密文存储到文件 %s 中。\n", filename);
// 从文件中读取密文并解密输出
fp = fopen(filename, "r");
if (fp == NULL) {
printf("无法打开文件 %s 进行读取。\n", filename);
return 1;
}
fgets(encrypted, MAX_INPUT_LENGTH, fp);
encrypted[strcspn(encrypted, "\n")] = '\0'; // 去除fgets读取字符串时末尾自带的换行符
fclose(fp);
decrypt(encrypted, decrypted);
printf("解密后的明文为:\n%s\n", decrypted);
return 0;
}
/**
* 将输入字符串按规律加密成密码。
*
* @param input 输入字符串
* @param output 输出密码
*/
void encrypt(char* input, char* output) {
int len = strlen(input);
for (int i = 0; i < len; i++) {
char c = input[i];
if (isalpha(c)) {
if (isupper(c)) {
output[i] = 'A' + ('Z' - c);
} else {
output[i] = 'a' + ('z' - c);
}
} else {
output[i] = c;
}
}
output[len] = '\0';
}
/**
* 将密码解密成明文。
*
* @param input 输入密码
* @param output 输出明文
*/
void decrypt(char* input, char* output) {
int len = strlen(input);
for (int i = 0; i < len; i++) {
char c = input[i];
if (isalpha(c)) {
if (isupper(c)) {
output[i] = 'A' + ('Z' - c);
} else {
output[i] = 'a' + ('z' - c);
}
} else {
output[i] = c;
}
}
output[len] = '\0';
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 1000
int main() {
char diary[MAX_LEN];
char cipher[MAX_LEN];
char ch;
int i, len;
// 读取日记
printf("Please enter your diary:\n");
fgets(diary, MAX_LEN, stdin);
// 加密
len = strlen(diary);
for (i = 0; i < len; i++) {
ch = diary[i];
if (ch >= 'A' && ch <= 'Z') {
cipher[i] = 'A' + ('Z' - ch);
} else if (ch >= 'a' && ch <= 'z') {
cipher[i] = 'a' + ('z' - ch);
} else {
cipher[i] = ch;
}
}
cipher[i] = '\0';
// 存储到文件
FILE *fp = fopen("Diary.txt", "w");
if (fp == NULL) {
printf("Failed to open file.\n");
exit(1);
}
fputs(cipher, fp);
fclose(fp);
// 从文件中读取密文并输出
fp = fopen("Diary.txt", "r");
if (fp == NULL) {
printf("Failed to open file.\n");
exit(1);
}
printf("Cipher text:\n");
while ((ch = fgetc(fp)) != EOF) {
printf("%c", ch);
}
fclose(fp);
return 0;
}