您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在C++中,可以使用标准库中的<fstream>
和<iostream>
头文件来处理文件的读取和写入
encrypt.cpp
的文件,然后将以下代码粘贴到文件中:#include <iostream>
#include <fstream>
#include <string>
#include <vector>
std::string encrypt(const std::string& input, const std::string& key) {
std::string output;
for (size_t i = 0; i < input.size(); ++i) {
output += static_cast<char>(input[i] + key[i % key.size()]);
}
return output;
}
void encryptFile(const std::string& inputFile, const std::string& outputFile, const std::string& key) {
std::ifstream in(inputFile, std::ios::binary);
if (!in) {
std::cerr << "Error opening input file: " << inputFile << std::endl;
return;
}
std::ofstream out(outputFile, std::ios::binary);
if (!out) {
std::cerr << "Error opening output file: " << outputFile << std::endl;
return;
}
std::string line;
while (std::getline(in, line)) {
std::string encryptedLine = encrypt(line, key);
out << encryptedLine << std::endl;
}
in.close();
out.close();
}
int main() {
std::string inputFile = "input.txt";
std::string outputFile = "output.txt";
std::string key = "secret";
encryptFile(inputFile, outputFile, key);
std::cout << "File encrypted successfully!" << std::endl;
return 0;
}
decrypt.cpp
的文件,然后将以下代码粘贴到文件中:#include <iostream>
#include <fstream>
#include <string>
#include <vector>
std::string decrypt(const std::string& input, const std::string& key) {
std::string output;
for (size_t i = 0; i < input.size(); ++i) {
output += static_cast<char>(input[i] - key[i % key.size()]);
}
return output;
}
void decryptFile(const std::string& inputFile, const std::string& outputFile, const std::string& key) {
std::ifstream in(inputFile, std::ios::binary);
if (!in) {
std::cerr << "Error opening input file: " << inputFile << std::endl;
return;
}
std::ofstream out(outputFile, std::ios::binary);
if (!out) {
std::cerr << "Error opening output file: " << outputFile << std::endl;
return;
}
std::string line;
while (std::getline(in, line)) {
std::string decryptedLine = decrypt(line, key);
out << decryptedLine << std::endl;
}
in.close();
out.close();
}
int main() {
std::string inputFile = "output.txt";
std::string outputFile = "decrypted.txt";
std::string key = "secret";
decryptFile(inputFile, outputFile, key);
std::cout << "File decrypted successfully!" << std::endl;
return 0;
}
encrypt.cpp
和decrypt.cpp
:g++ encrypt.cpp -o encrypt
g++ decrypt.cpp -o decrypt
encrypt
程序,将一个名为input.txt
的文件加密为output.txt
:./encrypt
decrypt
程序,将加密后的output.txt
文件解密为decrypted.txt
:./decrypt
这样,你就可以使用C++轻松地实现文件的加密和解密功能了。请注意,这里的示例仅用于演示目的,实际应用中可能需要考虑更多的安全因素。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。