#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>#define MAX_CHAR 256 // 定义字符数组的最大长度void encryptFile(const char* inputFile, const char* outputFile, int shift) {
FILE* input = fopen(inputFile, "r");
if (input == NULL) {
printf("Failed to open input file.\n");
exit(1);
}
FILE* output = fopen(outputFile, "w");
if (output == NULL) {
printf("Failed to create output file.\n");
fclose(input);
exit(1);
}
char ch;
while ((ch = fgetc(input)) != EOF) {
if (isalpha(ch)) { // 如果是字母,则进行移位加密
ch = ((ch - 'A' + shift) % 26) + 'A';
}
fputc(ch, output); // 将加密后的字符写入输出文件
}
fclose(input);
fclose(output);
}
void decryptFile(const char* inputFile, const char* outputFile) {
FILE* input = fopen(inputFile, "r");
if (input == NULL) {
printf("Failed to open input file.\n");
exit(1);
}
FILE* output = fopen(outputFile, "w");
if (output == NULL) {
printf("Failed to create output file.\n");
fclose(input);
exit(1);
}
char ch;
while ((ch = fgetc(input)) != EOF) {
if (isalpha(ch)) { // 如果是字母,则进行移位解密
ch = ((ch - 'A' - 300 + 26) % 26) + 'A';
}
fputc(ch, output); // 将解密后的字符写入输出文件
}
fclose(input);
fclose(output);
}
int main() {
const char* inputFile = "input.txt"; // 输入文件名
const char* encryptedFile = "encrypted.txt"; // 加密后的文件名
const char* decryptedFile = "decrypted.txt"; // 解密后的文件名
int shift = 300; // 移位数
// 对文件进行加密操作
encryptFile(inputFile, encryptedFile, shift);
printf("Encryption completed.\n");
// 对文件进行解密操作,还原为原始内容
decryptFile(encryptedFile, decryptedFile);
printf("Decryption completed.\n");
return 0;
}