您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。