"#include \n#include \n#include \n\n// 函数声明\nvoid encodeFile(const std::string& filePath);\nvoid decodeFile(const std::string& filePath);\n\nint main()\n{\n // 文件路径\n std::string filePath = "path/to/file.txt";\n \n // 检查文件是否以乱码形式存在\n std::ifstream file(filePath);\n std::string line;\n bool isEncoded = false;\n \n while (std::getline(file, line))\n {\n // 检查文件是否包含乱码字符\n for (char c : line)\n {\n if (c < 0) // ASCII码小于0的字符视为乱码\n {\n isEncoded = true;\n break;\n }\n }\n \n if (isEncoded)\n {\n break;\n }\n }\n \n file.close();\n \n // 根据情况执行编码或解码操作\n if (!isEncoded)\n {\n encodeFile(filePath);\n std::cout << "文件已乱码化" << std::endl;\n }\n else\n {\n decodeFile(filePath);\n std::cout << "文件已恢复为非乱码状态" << std::endl;\n }\n \n return 0;\n}\n\n// 编码文件\nvoid encodeFile(const std::string& filePath)\n{\n std::ifstream inputFile(filePath);\n std::ofstream encodedFile("path/to/encoded_file.txt");\n std::string line;\n \n while (std::getline(inputFile, line))\n {\n std::string encodedLine;\n \n // 对每个字符进行编码操作(示例:将字符的ASCII码加1)\n for (char c : line)\n {\n encodedLine += c + 1;\n }\n \n encodedFile << encodedLine << std::endl;\n }\n \n inputFile.close();\n encodedFile.close();\n \n // 删除原文件\n remove(filePath.c_str());\n \n // 重命名编码后的文件\n rename("path/to/encoded_file.txt", filePath.c_str());\n}\n\n// 解码文件\nvoid decodeFile(const std::string& filePath)\n{\n std::ifstream encodedFile(filePath);\n std::ofstream decodedFile("path/to/decoded_file.txt");\n std::string line;\n \n while (std::getline(encodedFile, line))\n {\n std::string decodedLine;\n \n // 对每个字符进行解码操作(示例:将字符的ASCII码减1)\n for (char c : line)\n {\n decodedLine += c - 1;\n }\n \n decodedFile << decodedLine << std::endl;\n }\n \n encodedFile.close();\n decodedFile.close();\n \n // 删除原文件\n remove(filePath.c_str());\n \n // 重命名解码后的文件\n rename("path/to/decoded_file.txt", filePath.c_str());\n}\n"。\n\n请注意,这个示例程序对文件进行了简单的编码和解码操作,只是将字符的ASCII码加1和减1。如果您需要更高的加密程度,请使用更高级的加密算法来代替示例中的简单操作。

C++ 文件编码解码程序:实现乱码化和恢复功能

原文地址: https://www.cveoy.top/t/topic/qBaa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录