c++文件加密问题记录与解决
(第一篇博客,希望大家多多支持!还是初学者,若有问题或更好的见解请在评论区指出,欢迎交流!)
一、问题描述
Write an encryption program that reads from cin (a file)and writes the encoded characters to cout (a file).
You might use this simple encryption scheme: the encrypted form of a character c is c^key[i], where key is a string passed as a command-line argument. The program uses the characters in key in a cyclic manner until all the input has been read. Re-encrypting encoded text with the same key produces the original text. If no key (or a null string) is passed, then no encrption is done.
二、问题解决
1.thinking
创建三个文件:in.txt(用于读入)、out.txt(加密结果存储)、original.txt(解密结果存储)。
读入文件,进行后续加密解密操作;若读入失败,进行异常处理。
2.important
①.了解c++的位运算(此处主要为 ^ 异或运算)
②.关于文件的一些处理
3.process
①.关于 异或 运算
可以看出,异或运算返回值是int,而char ^ int实际对char进行了隐式类型转换。
另外,我们需要以char类型从in.txt文件中读入,以int类型从out.txt中读入。
异或运算有一些特殊用途:1.一个数异或两次是本身。2.一个数与0异或会保留原值(1001 1001 ^ 0000 0000 -> 1001 1001)
②.关于文件的读入和EOF
关于EOF的详细解释:https://www.cnblogs.com/dolphin0520/archive/2011/10/13/2210459.html
在文件读入时,每次读入之后都应判断是否读到EOF。当然写法根据具体情况而定。在此题中,若将读入写入循环体,判断条件为while(!f_in.eof())会出现不可预测的问题,即使文件已经读完,但循环不会终止!
4.result
分享源码
1 #include<iostream> 2 #include<fstream> 3 #include<cstring> 4 5 using namespace std; 6 7 int main(int argc,char** argv) 8 { 9 ifstream fin("in.txt"); 10 if (!fin.is_open()) { 11 cout << "Can't open file \"in.txt\""; 12 return -1; 13 } 14 15 fstream fout("out.txt"); 16 if (!fout.is_open()) { 17 cout << "Can't open file \"out.txt\""; 18 return -1; 19 } 20 21 if(strlen(argv[1]) == 0){ //若没receive到命令行参数,则不进行加密解密 22 string temp; 23 cout<<"No key . No encryption ."<<endl; 24 while(fin>>temp){ 25 fout<<temp; 26 } 27 return 0; 28 } 29 30 char temp; 31 int i = 0; 32 33 while (fin.get(temp)) //加密运算 34 { 35 fout << (temp ^ argv[1][strlen(argv[1]) - i % strlen(argv[1])]) << ' '; 36 i++; 37 } 38 39 fin.close(); 40 fout.close(); 41 42 cout << "Encryption has done ." << endl 43 << "Now begin re-encrypting ." << endl; 44 45 ifstream f_in("out.txt"); 46 if (!f_in.is_open()) { 47 cout << "Can't open file \"out.txt\""; 48 return -1; 49 } 50 51 ofstream f_out("original.txt"); 52 if (!f_out.is_open()) { 53 cout << "Can't open file \"original.txt\""; 54 return -1; 55 } 56 57 i = 0; 58 int temp_1; 59 while (f_in >> temp_1) { //解密运算,此处需要进行强制类型转换输出字符 60 f_out << char((temp_1 ^ argv[1][strlen(argv[1]) - i % strlen(argv[1])])); 61 i++; 62 } 63 64 cout << "Re-encryption has done." << endl; 65 return 0; 66 }